Assume a thread is started from the main method. What happens if an exception is thrown in the thread but not handled within the thread?
Is it possible to propagate the exception back to the main method?
解决方案
We are talking about unchecked exceptions thrown from Thread.run method.
By default, you will get sth like this in system error:
Exception in thread "Thread-0" java.lang.RuntimeException
at Main$1.run(Main.java:11)
at java.lang.Thread.run(Thread.java:619)
This is the result of printStackTrace for unhandled exceptions. To handle it, you can add your own UncaughtExceptionHandler:
Thread t = new Thread(new Runnable(){
public void run() {
throw new RuntimeException();
}
});
t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
System.out.println("exception " + e + " from thread " + t);
}
});
t.start();
To set handler for all threads use a static method Thread.setDefaultUncaughtExceptionHandler.