a glob of nerdishness

June 16, 2007

Global C++ Exception Handling

written by natevw @ 12:01 pm

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.

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.