多线程的异常处理 在线程中如果出现异常想要额外进行一些操作的话,可以使用线程的异常处理机制,UncaughtExceptionHandler,这是线程的一个子接口,当一个未捕获的异常导致线程中断的时候JVM会使用thread.getUncaughtExceptionHandler()来查询线程的uncaughtExceptionHandler并将线程和异常作为参数传递给uncaughtException方法
1 2 3 4 5 6 7 8 9 10 11 12 @FunctionalInterface public interface UncaughtExceptionHandler { void uncaughtException (Thread t, Throwable e) ; }
如果当前线程没有显示的调用thread.setUncaughtExceptionHandler()方法设置处理器时,会默认使用该线程的线程组的uncaughtException()方法,线程组是实现了UncaughtExceptionHandler接口的,线程组是在线程实例化时就进行指定的
1 public class ThreadGroup implements Thread .UncaughtExceptionHandler
自定义Handler 如何自定义handler并进行使用呢,那当然是要实现UncaughtExceptionHandler接口了,重写uncaughtException()方法即可
1 2 3 4 5 6 7 8 class MyExceptionHandler implements Thread .UncaughtExceptionHandler { @Override public void uncaughtException (Thread t, Throwable e) { System.out.println(t.getName()+"抛出异常" +e.getMessage()); e.printStackTrace(); } }
在实例化线程的时候进行指定handler即可
1 thread.setUncaughtExceptionHandler(new MyExceptionHandler());
代码示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 public class TestExceptionHandler { public static void main (String[] args) { TestExceptionHandler test = new TestExceptionHandler(); Thread thread = new Thread(test.new MyThread () ) ; thread.setUncaughtExceptionHandler(new MyExceptionHandler()); thread.start(); } class MyThread implements Runnable { @Override public void run () { try { Thread.sleep(2000 ); } catch (InterruptedException e) { e.printStackTrace(); } int i = 1 /0 ; } } } class MyExceptionHandler implements Thread .UncaughtExceptionHandler { @Override public void uncaughtException (Thread t, Throwable e) { System.out.println(t.getName()+"抛出异常" +e.getMessage()); e.printStackTrace(); } }
例子不是一个好例子,但是主要就是展示一下如何使用,场景自己把握