Global C++ Exception Handling
It’s easy to handle uncaught exceptions at a global level in a C++ program. Most compilers, if not all, provide a function called std::set_terminate(). This lets you register a function that gets called when the program terminates unexpectedly due to an error. This function does not take any arguments, but can re-throw any current exception:
void catch_global() {
try {
throw;
}
catch (const YourPrintableException& e) {
std::cerr << "Exiting due to error: " << e << std::endl;
}
catch (...) {
std::cerr << "XQI ERROR -42: UNEXPECTED OCCURRENCE" << std::endl;
}
abort();
}
int main() {
std::set_terminate(catch_global);
if (true) throw "up";
else return 0;
}
While this shouldn't replace good error handling practices throughout your code, it can be a handy way for your program to put some last words on the record before it kicks the bucket.
One disclaimer: I'm not completely sure that set_terminate() is an official part of the C++ standard. It's in Thinking in C++ but not the C++ FAQ-Lite, the big C++ reference or the light C++ reference. Official standard or not, it seems to be widespread. You can find documentation on set_terminate() via GNU, IBM or MSDN.