Thread getDefaultUncaughtExceptionHandler() 方法



描述

Java Thread getDefaultUncaughtExceptionHandler() 方法返回当线程因未捕获异常而突然终止时调用的默认处理程序。如果返回值为 null,则没有默认处理程序。

声明

以下是java.lang.Thread.getDefaultUncaughtExceptionHandler() 方法的声明

public static Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler()

参数

返回值

此方法不返回值。

异常

示例:获取线程的 DefaultUncaughtExceptionHandler

以下示例演示了 Java Thread getDefaultUncaughtExceptionHandler() 方法的用法。在这个程序中,我们通过实现 Runnable 接口创建了一个线程类 AdminThread。在 run 方法中,我们抛出一个 RuntimeException。在 main 方法中,我们创建了一个 AdminThread 类的新的线程,并使用 setDefaultUncaughtExceptionHandler() 方法设置了一个未捕获异常处理程序,该处理程序打印抛出的异常。现在使用 getDefaultUncaughtExceptionHandler(),检索并打印异常处理程序。

使用 start() 方法启动线程,结果将打印到控制台。

package com.tutorialspoint;

public class ThreadDemo {

   public static void main(String[] args) {

      Thread t = new Thread(new AdminThread());
      t.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

         public void uncaughtException(Thread t, Throwable e) {
            System.out.println(t + " throws exception: " + e);
         }
      });
      // this will call run() function
      t.start();
	  
      /* returns the handler invoked when this thread abruptly 
         terminates due to an uncaught exception. */
      Thread.UncaughtExceptionHandler handler = 
      t.getDefaultUncaughtExceptionHandler();
      System.out.println(handler);
   }
}

class AdminThread implements Runnable {

   public void run() {
      throw new RuntimeException();
   }
} 

输出

让我们编译并运行上述程序,这将产生以下结果:

com.tutorialspoint.ThreadDemo$1@28a418fc
Thread[#21,Thread-0,5,main] throws exception: java.lang.RuntimeException
java_lang_thread.htm
广告
© . All rights reserved.