How to Use the Try and Catch Blocks in C++? (original) (raw)

Last Updated : 10 Jun, 2026

In C++, try and catch blocks are used for exception handling. They allow programs to respond to runtime errors in a controlled manner instead of terminating unexpectedly. When an exception is thrown inside a try block, execution is transferred to a matching catch block for handling.

#include using namespace std;

int main(){ try { throw 10; } catch(int num) { cout << "Exception Caught: " << num; }

return 0;

}

`

Output

Exception Caught: 10

**Explanation: The throw statement generates an exception, which is caught and handled by the catch block.

try_and_catch

Try and Catch

Syntax

try {

// Code that may throw an exception

}

catch (exception_type e) {

// Handle the exception

}

**Where:

**Example: Using Try and Catch Blocks

C++ `

#include #include 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

**Explanation

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