package com.dwz.concurrency.chapter11; /** * Thread的run方法是不能throw出异常的,只能在日志或者console中打印出来 */ public class ThreadException { private final static int A = 10; private final static int B = 0; public static void main(String[] args) { Thread t = new Thread(()->{ try { Thread.sleep(5_000); int result = A/B; System.out.println(result); } catch (InterruptedException e) { e.printStackTrace(); } }); //该方法可以在线程外面捕获到异常 t.setUncaughtExceptionHandler((thread, e)->{ System.out.println(e); System.out.println(thread); }); t.start(); } }
使用了setUncaughtExceptionHandler后会把异常处理交给setUncaughtExceptionHandler,线程里面的异常不再输出日志信息