Try-Catch Blocks
Basic exception handling
Interview Relevant: Error handling
Try-Catch Blocks
Handle runtime errors gracefully with exceptions.
Code Examples
Basic try-catch exception handling.
cpp
1try {
2 int* arr = new int[1000000000000];
3} catch (const bad_alloc& e) {
4 cout << "Memory allocation failed: " << e.what() << endl;
5}
6
7// Catch multiple exception types
8try {
9 riskyOperation();
10} catch (const runtime_error& e) {
11 cout << "Runtime error: " << e.what() << endl;
12} catch (const logic_error& e) {
13 cout << "Logic error: " << e.what() << endl;
14} catch (...) {
15 cout << "Unknown exception" << endl;
16}
17
18// Exception handling order: most specific first!
19try {
20 throw runtime_error("error");
21} catch (const exception& e) {
22 // Catches all standard exceptions
23} catch (const runtime_error& e) {
24 // Never reached! More specific should come first
25}