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:
- The code inside the try block is executed.
- 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.
- The first matching catch block is executed, and any remaining catch blocks are skipped.
- 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:
- The program attempts to perform a division operation with the values 10 (numerator) and 0 (denominator).
- It employs a try block to enclose the code that might generate exceptions.
- 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”.
- If the denominator is not zero, it calculates the result of the division (numerator / denominator) and displays it using cout.
- 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().
- 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.
- 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.