Java Thread 如何处理未捕获的异常?
Java Thread是不允许异常抛出到本线程之外的,Runnable接口的public abstract void run()是不允许throws Exception的,这在编译时就通不过。
线程异常处理方式两种:
- try/catch
这种方式很简单很暴力,但是代码不太优雅。一般我们只捕获编译时异常。更优雅的做法就是第二种通过UncaughtExceptionHandler接口实现。 -
Thread.UncaughtExceptionHanlder
-
-
- 在创建线程的时候进行设置
-
public class ThreadExceptionCatch { public static void main(String[] args) { Thread t = new Thread() { @Override public void run() { //todo something.... throw new RuntimeException("异常了"); } }; t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { System.out.println(t.getName()+"发生异常:"+e); } }); t.start(); } }
-
-
- 使用Executors创建线程时,还可以在ThreadFactory中设置
-
public class ThreadExceptionCatch { public static void main(String[] args) { ExecutorService executorService= Executors.newFixedThreadPool(10, new ThreadFactory() { @Override public Thread newThread(Runnable r) { Thread thread=new Thread(r); //设置异常处理器 thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { System.out.println(e); } }); return thread; } }); //执行 executorService.execute(new Runnable() { @Override public void run() { throw new RuntimeException("异常了"); } }); } }
-
-
- 设置Thread全局默认UnCaughtExceptionHandler
-
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { System.out.println(e); } });
defaultUncaughtExceptionHandler是Thread的静态变量:
private static volatile UncaughtExceptionHandler defaultUncaughtExceptionHandler;