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 in main
. I created a catch for 3 things: myException
(an in house exception), std::exception
, and ...
(catch all exceptions).
As part of the shared objects execution, many pthreads
are created. When a thread throws an exception, it is not caught by main
. Is this the standard behavior? How can I catch all exceptions, no matter what thread they are thrown from?
An uncaught exception will cause the thread to exit. When it bubbles to the top of Thread. run() it will be handled by the Thread's UncaughtExceptionHandler. By default, this will merely print the stack trace to the console.
Answer. Yes, it can be done by using Thread. UncaughtExceptionHandler. When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler usingThread.
The nothrow constant value is used as an argument for operator new and operator new[] to indicate that these functions shall not throw an exception on failure but return a null pointer instead.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With