处理非正常终止的错误
1. 最简单通过主动的内部函数的方法捕获
package concurrent._ThreadPool._UnnormalThread; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; //一种主动的方法捕获异常 public class Demo { public static void main(String[] args) { Catch aCatch = new Catch(); Catch.ThreadA threadA = aCatch.new ThreadA(); ExecutorService executorService = Executors.newFixedThreadPool(3); executorService.execute(threadA); } } class Catch{ private void threadDeal(Throwable t){ System.out.println("Exception" + t.getMessage()); } class ThreadA implements Runnable{ @Override public void run() { Throwable throwable = null; try{ System.out.println(3/0); }catch (Throwable t){ //Error 和 Exception都是Throwable的子类 throwable = t; }finally { threadDeal(throwable); } } } }
2. 通过设置一个默认的UncaughtExceptionHandler来处理所有的异常
package concurrent._ThreadPool._UnnormalThread; import java.lang.Thread.UncaughtExceptionHandler; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; //一种主动的方法捕获异常 public class Demo2 { public static void main(String[] args) { Thread.setDefaultUncaughtExceptionHandler(new MyExceptionhandler()); ThreadA threadA = new ThreadA(); ExecutorService executorService = Executors.newFixedThreadPool(3); executorService.execute(threadA); } } class MyExceptionhandler implements UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { System.out.println(e.getMessage()); } } class ThreadA implements Runnable{ @Override public void run() { System.out.println(3/0); } }
3.