包java.lang.Thread.getDefaultUncaughtExceptionHandler()中提供了此方法。
如果任何线程引发异常并在我们未编写任何代码处理未捕获的异常的情况下任何线程异常终止,则使用此方法返回Default处理程序。
此方法是静态的,因此也可以使用类名访问此方法。
该方法的返回类型是Thread.UncaughtExceptionHandler,它提供了默认的处理程序来处理未捕获的异常。
如果我们忘记编写未捕获的异常代码,则此方法最合适,因此,如果线程突然终止,它将自动成为默认的处理程序调用。
如果此方法未引发任何异常(意味着正常终止线程),则此方法返回null。
语法:
static Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){
}参数:
在Thread方法中,我们不传递任何对象作为参数。
返回值:
此方法的返回类型为Thread.UncaughtExceptionHandler,它返回未捕获异常的默认处理程序,否则,如果没有默认值,则返回null表示正常终止。
getDefaultUncaughtExceptionHandler()方法示例/* 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 DefaultExceptionHandler extends Thread {
//覆盖run()Thread类
public void run() {
//显示最终用户的消息
System.out.println("The name of this thread is " + " " + Thread.currentThread().getName());
}
public static void main(String[] args) {
//创建一个DefaultExceptionHandler类的对象
DefaultExceptionHandler deh =
new DefaultExceptionHandler();
//创建一个Thread类的对象
Thread th1 = new Thread(deh);
Thread th2 = new Thread(deh);
//线程类start()方法将调用,并且最终
th1.start();
th2.start();
/* getDefaultUncaughtExceptionHandler() will return
the default handler for uncaught exception and
create a reference of Thread.UncaughtExceptionHandler
*/
Thread.UncaughtExceptionHandler ueh = Thread.getDefaultUncaughtExceptionHandler();
System.out.println("The Default handler for the thread is = " + ueh);
}
}输出结果
E:\Programs>javac DefaultExceptionHandler.java E:\Programs>java DefaultExceptionHandler The Default handler for the thread is = null The name of this thread is Thread-1 The name of this thread is Thread-2