I have a pretty large application that dynamically loads shared objects and executes code in the shared object. As a precaution, I put a try/catch around almost everything i
Will main() catch exceptions thrown from threads?
No
When a thread throws an exception, it is not caught by main. Is this the standard behavior?
Yes, this is standard behaviour.
To catch an exception originating in thread X
, you have to have the try
-catch
clause in thread X
(for example, around everything in the thread function, similarly to what you already do in main
).
For a related question, see How can I propagate exceptions between threads?
Consider that throwing an exception unwinds the stack. Each thread has its own stack. You will have to place a try/catch block in each thread function (i.e. in the entry point of each thread).
Your question is asking for something that isn't conceptually possible.
Try blocks are defined as dynamic constructs of the stack. A try block catches exceptions thrown by code reached dynamically, by call, from its contents.
When you create a new thread, you create a brand-new stack, that is not at all part of the dynamic context of the try block, even if the call to pthread_create is inside the try.
No, main will not catch exceptions thrown from other threads. You would need to use a non-standard, platform specific facility that addresses unhandled exceptions in order to aggregate the handling the way you are describing.
When I build such applications, I make sure each active object has its own top-level exception handling block, precisely to prevent the entire application from exploding if one thread fails. Using a platform-specific catch all I think begs for your overall code / solution to be sloppy. I would not use such a thing.