How to catch all uncaught exceptions from different threads in one place during development?

I have a small application with multiple threads with GUI and sockets. During development, I found that sometimes there are a few exceptions that are not caught and are not logged into the system . I have to look at the console to get them, if any.

Is there a way to catch these uncaught exceptions from different threads (including EDT) in one place, speaking in main () and writing them down? I put try-catch in main () to catch Throwable , but it does not work.

EDIT:

More specifically, I have Executors.newCachedThreadPool () with Runnable . I do not want to use Callable in many cases, because I do not want to block my calling thread. Then how can I catch exceptions from these Runnables?

And also how can I catch the ncaught exception from Swing EDT ?

+5
source share
2 answers

I would suggest installing a custom handler of type UncaughtExceptionHandler for thrown exceptions using the Thread.setDefaultUncaughtExceptionHandler method. This handler will be called by the JVM when the thread is about to terminate due to an uncaught exception.

Thread.setDefaultUncaughtExceptionHandler((Thread t, Throwable e) -> { System.out.println(t + " throws exception: " + e); }); 

UPD:

Regarding the Swing EDT case, I think there is a nice answer here.

+6
source

It is not a simple problem in a large complex program, because there is no way to catch an exception in another thread from the one that threw it. You must make sure that each thread in the program has a handler that will catch all exceptions and report them.

This is easy enough if you manage code that creates all the threads, but harder if you call library procedures that create threads on your behalf. If you're lucky, the libraries will allow you to provide ThreadFactory , which will allow your code to gain control when creating a new thread.

Even if you can make sure that each thread has an exception handler that does the right thing, you can still have some code hiding somewhere (maybe in some third-party library that you are calling) which catches the exception and ignores it.

Good luck

-1
source

Source: https://habr.com/ru/post/1237848/


All Articles