Topic 70 of 83
Try/Catch
Overview
The `try` block contains the code that might fail. The `throw` statement signals that an error occurred. The `catch` block catches the thrown error and handles it.
Syntax
cpp
try {
int denominator = 0;
if (denominator == 0) {
throw "Cannot divide by zero!"; // Throwing a string literal
}
cout << 10 / denominator;
}
catch (const char* errorMessage) {
cout << "Error Caught: " << errorMessage << endl;
}Common Pitfalls
- Throwing an exception inside a destructor. If a destructor throws an exception while the stack is already unwinding from a previous exception, the program will call `std::terminate()` and crash instantly.
Interview Tips
- When an exception is thrown, the program skips all remaining code in the `try` block and jumps directly to the matching `catch` block (this process is called stack unwinding).
Real-World Example
Handling basic division errors.
example
cpp
#include <iostream>
using namespace std;
int main() {
int a = 10, b = 0;
try {
if (b == 0) throw 404; // Throwing an integer
cout << a / b << endl;
}
catch (int errorCode) {
cout << "Fatal Error! Code: " << errorCode << endl;
}
cout << "Program continues running safely.\n";
return 0;
}