Reputation: 23419
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?
Upvotes: 12
Views: 7804
Reputation: 16898
It can if you assign it to a ThreadGroup that implements the uncaughtException(Thread, Throwable) method.
Upvotes: 0
Reputation: 34721
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());
Upvotes: 10
Reputation: 20777
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())
Upvotes: 1