getUncaughtExceptionHandler()包java.lang.Thread.getUncaughtExceptionHandler()中提供了此方法。
如果任何线程由于未捕获的异常而异常终止(如果引发任何异常),则此方法用于返回调用的处理程序。
此方法不是静态的,因此也无法使用类名访问此方法。
此方法的返回类型为Thread.UncaughtExceptionHandler,它提供当线程由于未捕获的异常而异常终止时调用的处理程序。
如果此方法未引发任何异常(意味着正常终止线程),则此方法返回null。
语法:
Thread.UncaughtExceptionHandler getUncaughtExceptionHandler(){
}参数:
在Thread方法中,我们不传递任何对象作为参数。
返回值:
此方法的返回类型为Thread.UncaughtExceptionHandler,当突然终止线程时,它将返回未捕获异常的处理程序;否则,如果没有错误意味着正常终止,则返回null。
getUncaughtExceptionHandler()方法示例/* We will use Thread class methods so we are importing
the package but it is not mandate
because it is imported by default
*/
import java.lang.Thread;
class UncaughtExceptionHandlerClass extends Thread {
static Thread th1;
//覆盖run()Thread类
public void run() {
//显示最终用户的消息
System.out.println("The name of this thread is " + " " + Thread.currentThread().getName());
// getUncaughtExceptionHandler()将返回处理程序
//对于线程异常终止时未捕获的异常
//并创建Thread.UncaughtExceptionHandler的引用
Thread.UncaughtExceptionHandler ueh = th1.getUncaughtExceptionHandler();
System.out.println("The handler for the thread is = " + ueh);
}
public static void main(String[] args) {
//创建一个UncaughtExceptionHandlerClass类的对象
UncaughtExceptionHandlerClass uehc =
new UncaughtExceptionHandlerClass();
//创建一个Thread类的对象
th1 = new Thread(uehc);
//线程类start()方法将调用,并且最终
th1.start();
}
}输出结果
E:\Programs>javac UncaughtExceptionHandlerClass.java E:\Programs>java UncaughtExceptionHandlerClass The name of this thread is Thread-1 The handler for the thread is = java.lang.ThreadGroup[name=main,maxpri=10]