Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ unhandled exceptions

Does C++ offer a way to 'show' something visual if an unhandled exception occurs?

What I want to do is to make something like assert(unhandled exception.msg()) if it actually happens (like in the following sample):

void foo() {
   throw std::exception("Message!");
}

int main() {
 foo();
}

I expect this kind of code not to terminate immediately (because exception was unhandled), rather show custom assertion message (Message! actually).

Is that possible?

like image 344
Yippie-Ki-Yay Avatar asked Sep 22 '10 23:09

Yippie-Ki-Yay


3 Answers

There's no way specified by the standard to actually display the message of the uncaught exception. However, on many platforms, it is possible anyway. On Windows, you can use SetUnhandledExceptionFilter and pull out the C++ exception information. With g++ (appropriate versions of anyway), the terminate handler can access the uncaught exception with code like:

   void terminate_handler()
   {
       try { throw; }
       catch(const std::exception& e) { log(e.what()); }
       catch(...) {}
   }

and indeed g++'s default terminate handler does something similar to this. You can set the terminate handler with set_terminate.

IN short, no there's no generic C++ way, but there are ways depending on your platform.

like image 50
Logan Capaldo Avatar answered Sep 21 '22 04:09

Logan Capaldo


Microsoft Visual C++ allows you to hook unhandled C++ exceptions like this. This is standard STL behaviour.

You set a handler via a call to set_terminate. It's recommended that your handler do not very much work, and then terminate the program, but I don't see why you could not signal something via an assert - though you don't have access to the exception that caused the problem.

like image 20
Steve Townsend Avatar answered Sep 23 '22 04:09

Steve Townsend


If you are using Windows, a good library for handling unhandled exceptions and crashes is CrashRpt. If you want to do it manually you can also use the following I wrote in this answer.

like image 36
Brian R. Bondy Avatar answered Sep 22 '22 04:09

Brian R. Bondy