Open In App

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

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.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++ 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.

Article Tags :