I have a not small multiple threads application with GUI and socket communications. During the development, I found sometimes there are some exceptions are not caught and logged. I have to stare at the console to get them if there is any.
Is there a way to catch those uncaught exceptions from different threads (including EDT) in one place, saying in main(), and log them? I do put a try-catch in main() to catch the Throwable but it doesn't work.
EDIT:
More specific, I have Executors.newCachedThreadPool() with Runnables. I don't want to use Callable in many cases because I don't want to block my calling thread. Then how can I catch exceptions from those Runnables?
And also how can I catch uncaught exception from the Swing EDT?
Exception handling in Thread : By default run() method doesn't throw any exception, so all checked exceptions inside the run method has to be caught and handled there only and for runtime exceptions we can use UncaughtExceptionHandler.
There does not exist a way in Java to use try/catch around your start() method to catch the exceptions thrown from a secondary thread and remain multithreaded.
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.
I would propose to set a custom handler of type UncaughtExceptionHandler for non-caught exceptions using method Thread.setDefaultUncaughtExceptionHandler. This handler will be invoked by JVM when thread is about to terminate due to an uncaught exception.
Thread.setDefaultUncaughtExceptionHandler((Thread t, Throwable e) -> {
System.out.println(t + " throws exception: " + e);
});
UPD:
As for Swing EDT case, I think there is nice answer here.
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