Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happens when a Thread throws an Exception?

If I invoke the run() method on a Thread and the run() method throws an uncaught Exception what would be the outcome ?

Who catches this Exception? Does the Exception even get caught?

like image 407
Geek Avatar asked Jul 28 '09 10:07

Geek


2 Answers

If there is an exception handler installed for the ThreadGroup, the JVM passes the exception to it. If it's an AWT thread, you can install an event handler for otherwise unhandled exceptions. Otherwise the JVM handles it.

Example of a thread group with a custom handler and how to use it:

public class MyThreadGroup extends ThreadGroup {
    public MyThreadGroup() {
        super("My Thread Group");
    }
    public void uncaughtException(Thread t, Throwable ex) {
        // Handle exception
    }
}

Thread t = new Thread(new MyThreadGroup(), "My Thread") { ... };
t.start();

Example of using an AWT exception handler:

public class MyExceptionHandler {
    public void handle(Throwable ex) {
        // Handle exception
    }
    public void handle(Thread t, Throwable ex) {
        // Handle exception
    }
}

System.setProperty("sun.awt.exception.handler", MyExceptionHandler.class.getName());
like image 168
Draemon Avatar answered Sep 22 '22 23:09

Draemon


If you've submitted the Runnable to an ExecutorService you can catch the Exception as wrapped inside a ExecutionException. (Highly recommended over simply calling run())

like image 35
Tim Avatar answered Sep 23 '22 23:09

Tim