My application uses a camera library which shall send images to my application continuously. Unfortunately this library starts a thread which throws an exception (or causes an exception to be thrown) and doesn’t handle it. As a result the entire application crashes. Is there a way to prevent the application from crashing? Can I install an exception handler on a thread externally?
Some details about my specific situation: There’s no function in the call stack of the crashing thread, that I have control over. I don’t even know what exactly the thread is there for. But I stop the program with the debugger, I can tell which thread it is, that is going to crash. Unfortunately, the thread crashes very randomly, sometimes it takes more than an hour until something happens. I’m using Visual Studio C++ 2010, the debugger tells me, it’s a std::bad_alloc.
You can trap the exception by installing a callback with SetUnhandledExceptionFilter. And kill the thread when it fires.
Nevertheless, the exception is a nasty one. The common cause for std::bad_alloc is not just running out of memory, it can also be triggered by a corrupted heap. Both are unrecoverable conditions, killing the thread doesn’t restore leaked memory and doesn’t un-corrupt the heap. Furthermore, you’ve leaked the thread’s stack by killing the thread. And the odds that you’ll get the camera going are very slight in general, it will very likely just bomb again quickly. Only consider trying this iff your program can continue to be useful without the camera.
Running it out of process so you can afford to lose the state entirely is an option, but the process interop you’ll need it painful and relatively expensive.
If you can’t get support from the vendor then you need to go shopping again.