捕获子线程异常的解决方案
1、手动在子线程的run方法里面try catch
2、利用UncaughtExceptionhandler
public void uncaughtException(Thread t, Throwable e) {if (parent != null) {parent.uncaughtException(t, e);} else {Thread.UncaughtExceptionHandler ueh =Thread.getDefaultUncaughtExceptionHandler();if (ueh != null) {ueh.uncaughtException(t, e);} else if (!(e instanceof ThreadDeath)) {System.err.print("Exception in thread \""+ t.getName() + "\" ");e.printStackTrace(System.err);}}
package com.imooc.thread_demo.uncaughtexception;/*** @Author: zhangjx* @Date: 2020/9/12 23:15* @Description:*/public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{private String name;public MyUncaughtExceptionHandler(String name) {this.name = name;}@Overridepublic void uncaughtException(Thread t, Throwable e) {System.out.println(name + "捕获" + t.getName() + " 线程异常,中止!");}}
package com.imooc.thread_demo.uncaughtexception;/*** @Author: zhangjx* @Date: 2020/9/12 23:19* @Description:*/public class UseMyUncaughtExceptionHandler {public static void main(String[] args) {Thread.setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler("自定义捕获器1"));new Thread(new SubThread()).start();}static class SubThread implements Runnable{@Overridepublic void run() {throw new RuntimeException("子线程运行异常!");}}}
