uncaughtException(Thread t, Throwable e)
Called by the Java Virtual Machine when a thread in this thread group stops because of an uncaught exception, and the thread does not have a specific Thread.UncaughtExceptionHandler installed.
public static interface Thread.UncaughtExceptionHandler
Interface for handlers invoked when a Thread abruptly terminates due to an uncaught exception.
When a thread is about to terminate due to an uncaught exception the Java Virtual Machine will query the thread for its UncaughtExceptionHandler using Thread.getUncaughtExceptionHandler() and will invoke the handler’s uncaughtException method, passing the thread and the exception as arguments. If a thread has not had its UncaughtExceptionHandler explicitly set, then its ThreadGroup object acts as its UncaughtExceptionHandler. If the ThreadGroup object has no special requirements for dealing with the exception, it can forward the invocation to the default uncaught exception handler.
线程退出关联Runnable对象的 run()方法后死亡。大多数情况中线程在执行完run()方法的所有代码后退出,但也有可能是由于未捕捉到的异常而退出。例如Java程序员们经常会遇 到NullPointerException异常,通常不会捕捉并处理该异常,因为程序在抛出NullPointerException异常后,一般无法 恢复。假设run()方法的执行过程中抛出NullPointerException异常,可能是由于该方法自身或由于该方法调用的其他代码引起的,再假 设未捕捉该异常会使线程死亡。
默认情况下,未捕捉的异常会在线程死亡前显示该线程的堆栈跟踪,不过也可以用未捕捉的异常处理程序来重写该行为。未捕捉的异常的处理方式取决于Java版本,Java 5及之后的版本能提供更大的灵活性。在Java 5之前,未捕捉的异常的自定义处理必须重写ThreadGroup类中的uncaughtException()方法,该方法具有如下两个参数:
● 出现未捕捉的异常的Thread对象
● 已抛出但未捕捉的Throwable对象
Java 5之前,线程在出现未捕捉的异常后会调用该线程关联的线程组uncaught- Exception()方法,该方法的默认实现就是显示该线程的堆栈跟踪。Java 5中的默认行为也一样,不过该版本修改了Thread类允许自定义每个线程的未捕捉异常行为,而不只是自定义特定ThreadGroup中关联线程的未捕 捉异常。具体的实现方式是在Thread类中定义一个UncaughtExceptionHandler接口,并在Thread类中加入 setUncaughtExceptionHandler()赋值方法和getUncaughtExceptionHandler()取值方法。 UncaughtExceptionHandler接口定义了一个uncaughtException()方法,该方法的签名与之前讲到的 ThreadGroup中的uncaughtException()方法一致,最后修改ThreadGroup类实现该接口。
根据Java 5中引入的新实现方式,线程出现未捕捉异常时会调用UncaughtException- Handler接口中的uncaughtException()方法。该行为与之前版本的行为一致,因为线程默认的未捕捉异常处理程序就是线程自身的 ThreadGroup对象。不过新改进的方式更具灵活性,允许修改线程的异常处理程序,做到每个线程都对应一个自定义异常处理程序。
References:
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ThreadGroup.html