Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 736
peterboston Avatar asked Dec 10 '15 13:12

peterboston


People also ask

How do you handle exceptions in multithreading?

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.

How can you catch an exception thrown by another thread in Java?

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.

What happens when an uncaught exception occurs in a thread?

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.


1 Answers

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.

like image 142
nogard Avatar answered Oct 29 '22 12:10

nogard