Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

try-catch block in C++

In C++, a try-catch block is used to handle exceptions. It helps you manage errors that may occur within a specific section of code.

Syntax

C++
try {
    // Code that might throw an exception
}
catch (ExceptionType1& ex1) {
    // Handle ExceptionType1
}
catch (ExceptionType2& ex2) {
    // Handle ExceptionType2
}
// ... More catch blocks for other exception types
catch (...) {
    // Handle any other exceptions not caught above
}

Explanation of the above code:

  1. The code inside the try block is executed.
  2. If an exception is thrown during the execution of the try block, the program immediately jumps to the corresponding catch block that matches the type of the thrown exception.
  3. The first matching catch block is executed, and any remaining catch blocks are skipped.
  4. If none of the catch blocks match the thrown exception, the program jumps to the catch (…) block, which is used for catching any unhandled exceptions.

Example

C++
#include <iostream>
#include <stdexcept>

using namespace std;

int main() {
    try {
        int numerator = 10;
        int denominator = 0;
        
        if (denominator == 0) {
            throw runtime_error("Division by zero");
        }
        
        int result = numerator / denominator;
        cout << "Result: " << result << endl;
    }
    catch (const runtime_error& e) {
        cerr << "Runtime error caught: " << e.what() << endl;
    }
    catch (const exception& e) {
        cerr << "An exception occurred: " << e.what() << endl;
    }

    return 0;
}

Explanation of the above code:

  1. The program attempts to perform a division operation with the values 10 (numerator) and 0 (denominator).
  2. It employs a try block to enclose the code that might generate exceptions.
  3. Inside the try block:
    • It checks if the denominator is zero using if (denominator == 0).
    • If the denominator is indeed zero, it throws a runtime_error exception with the message “Division by zero”.
  4. If the denominator is not zero, it calculates the result of the division (numerator / denominator) and displays it using cout.
  5. In case a runtime error occurs (division by zero), the program catches the runtime_error exception using the first catch block.
    • It uses cerr to display the error message “Runtime error caught: ” followed by the exception’s error message retrieved with e.what().
  6. If any other type of exception occurs, the second catch block catches and handles it.
    • It uses cerr to display a more general error message: “An exception occurred: ” followed by the exception’s error message.
  7. Finally, the program returns 0 to indicate successful execution.

Points to remember

  • Catch exceptions by reference.
  • Prioritize more specific exception types.
  • Avoid catching exceptions too broadly.
  • Nest try-catch blocks for different levels of handling.