Topic 71 of 83
Catch All
Overview
Sometimes you don't know exactly what type of exception might be thrown by third-party code. The catch-all block `catch(...)` acts as a safety net to catch literally anything.
Syntax
cpp
try {
// Risky code from an external library
externalLibraryCall();
}
catch (int e) {
cout << "Caught int exception";
}
catch (...) { // The ellipsis (...) means 'catch anything else'
cout << "Caught an unknown exception!";
}Common Pitfalls
- You cannot access the exception object in a `catch(...)` block because it has no named parameter. You know an error happened, but you don't know what it is.
Interview Tips
- A `catch(...)` block MUST be the very last catch block in a sequence. If you put it first, it will catch everything, and specific catch blocks below it will never run.
Real-World Example
Fallback mechanism for unknown failures.
example
cpp
#include <iostream>
using namespace std;
int main() {
try {
throw 3.14; // Throwing a double
}
catch (int e) {
cout << "Caught Int\n";
}
catch (char c) {
cout << "Caught Char\n";
}
catch (...) {
cout << "Caught something completely unexpected!\n";
}
return 0;
}