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?
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());
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With