Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
How to Create a Thread in C++?
Next article icon

How to Use the Try and Catch Blocks in C++?

Last Updated : 21 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, the try and catch blocks are used as a part of the exception handling mechanism which allows us to handle runtime errors. If the exceptions are not handled properly then the flow of the program is interrupted and the execution might fail. In this article, we will learn how to use try and catch blocks in C++.

Try and Catch Blocks in C++

In C++, a try block contains a set of statements where an exception might occur during the program's execution. It is followed by one or more catch blocks. A catch block is where we handle the exceptions, it specifies the type of exception it can handle and a response method to the exception. When an exception is thrown from a try block, the execution of the current function terminates immediately, and control is transferred to the matching catch block that handles the exception.

Syntax to Use Try and Catch Blocks in C++

try {     // Code that might throw an exception  }  catch (exception_type e) {     //catch the exception thrown from try block and handle it  }

Here, exception_type is the type of exception that the catch block can handle.

C++ Program to Use of Try and Catch Blocks

The following program illustrates how we can use try-catch blocks for exception handling in C++.

C++
// C++ Program to illustrate the use of try and catch blocks  #include <iostream> #include <stdexcept> using namespace std;  int main() {     // Declare two numbers     int num1 = 10;     int num2 = 0;      try {         // Throw a runtime_error exception if the         // denominator is zero         if (num2 == 0) {             throw runtime_error("Division by zero error");         }         cout << "Result of division: " << num1 / num2              << endl;     }     catch (const exception& e) {         // Catch the exception and print the error message         cerr << "Caught exception: " << e.what() << endl;     }      return 0; } 


Output

Caught exception: Division by zero error

Time Complexity:O(1)
Auxiliary Space: O(1)

Explanation: In the above example, we have performed division of two numbers. If the denominator is zero, it throws a runtime_error exception that is caught and handled in the catch block, and the program continues its execution without interruption. This is how we can use the try and catch blocks in C++ to handle exceptions effectively.


Next Article
How to Create a Thread in C++?
author
gaurav472
Improve
Article Tags :
  • C++ Programs
  • C++
  • cpp-exception
  • Exception Handling
  • C++-Exception Handling
  • CPP Examples
Practice Tags :
  • CPP

Similar Reads

  • How to Create a Thread in C++?
    A thread is a basic element of multithreading which represents the smallest sequence of instructions that can be executed independently by the CPU. In this article, we will discuss how to create a thread in C++. How to Create a Thread in C++?In C++, the std::thread is a class template that is used t
    2 min read
  • How to Detach a Thread in C++?
    In C++, a thread is a basic element of multithreading that represents the smallest sequence of instructions that can be executed independently by the CPU. In this article, we will discuss how to detach a thread in C++. What does Detaching a Thread mean?Detaching a thread means allowing the thread to
    2 min read
  • How to Throw and Catch Exceptions in C++?
    In C++, exception handling is a mechanism that allows us to handle runtime errors and exceptions are unusual conditions that occur at runtime. In this article, we will learn how to throw and catch exceptions in C++. Throw and Catch Exceptions in C++In C++ exceptions can be "thrown" when an error occ
    2 min read
  • How to Use cin.fail() Method in C++?
    In C++, the cin.fail() method is a part of <iostream> library that is used to check whether the previous input operation has succeeded or not by validating the user input. In this article, we will learn how to use cin.fail() method in C++. Example: Input: Enter an integer: aOutput: Invalid Inp
    2 min read
  • How to Use the ignore() Function in C++?
    In C++, the ignore() function is a part of std::basic_istream that is used to discard the characters in the stream until the given delimiter(including it) is reached and then extracts the left-out remainder. In this article, we will learn how to use the ignore() function in C++. C++ ignore() Functio
    2 min read
  • How to Throw an Exception in C++?
    In C++, exception handling is a mechanism that allows us to handle runtime errors and exceptions are objects that represent an error that occurs during the execution of a program. In this article, we will learn how to throw an exception in C++. Throw a C++ ExceptionThrowing an exception means sendin
    2 min read
  • How to Catch All Exceptions in C++?
    In C++, exceptions are objects that indicate you have an error in your program. They are handled by the try-catch block in C++. In this article, we will learn how to catch all the exceptions in C++. Catching All Exceptions in C++To catch all kinds of exceptions in our catch block in C++, we can defi
    2 min read
  • How to Throw a Custom Exception in C++?
    In C++, exception handling is done by throwing an exception in a try block and catching it in the catch block. We generally throw the built-in exceptions provided in the <exception> header but we can also create our own custom exceptions. In this article, we will discuss how to throw a custom
    2 min read
  • How to Add Message to Assert in C++
    In C++, assert is a debugging tool that allows the users to test assumptions in their code. The standard assert macro provided by <cassert> checks the condition and if the condition is evaluated as false, the assert statement terminates the program and prints an error message on the console al
    2 min read
  • How to Open and Close a File in C++?
    In C++, we can open a file to perform read and write operations and close it when we are done. This is done with the help of fstream objects that create a stream to the file for input and output. In this article, we will learn how to open and close a file in C++. Open and Close a File in C++ The fst
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences