利用UncaughtExceptionHandler捕获未try...catch到的异常

public class test {

public static void main(String[] args){
Thread thread = new Thread(new MyThread());
thread.setUncaughtExceptionHandler((Thread t,Throwable e)->{
System.out.println("出现异常");
System.out.println("线程名称:" + t.getName());
System.out.println("异常信息:" + e.getClass().getName() +":"+ e.getMessage());
System.out.println("线程状态:" +t.getState());
});
thread.start();
System.out.println("哈哈哈哈");

}
}

class MyThread implements Runnable{
@Override
public void run() {
System.out.println("啦啦啦啦啦啦啦啦啦啦");
System.out.println(1/0); //制造异常
System.out.println("啦啦啦啦啦啦啦啦啦啦");
}
}


运行main,控制台显示如图:

猜你喜欢

转载自www.cnblogs.com/yuanmaolin/p/10564699.html