views:

335

answers:

3

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 it even get caught ?

A: 

It can if you assign it to a ThreadGroup that implements the [uncaughtException][1] method.

[1]: http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadGroup.html#uncaughtException(java.lang.Thread, java.lang.Throwable)

Nate
+5  A: 

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());
Draemon
"Otherwise the JVM handles it." To be more precise, the thread that raised the exception will silently die.
Stephen C
@Stephen: Actually it prints the exception to stderr.
Draemon
Really? It must be JVM specific then ... because I've been tripped by the absence of a stack-trace.
Stephen C
Sure, it'll be implementation defined. I wasn't suggesting anyone relies on it. I just meant that it was up to the JVM to decide what to do with unhandled exceptions.
Draemon
A: 

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())

Tim