捕捉线程的异常

    技术2022-05-19  34

    线程的正常运行和销毁一般都是用java.util.concurrent.ExecutorService,这个接口能提供线程很多的帮助

     

    简单的线程异常捕捉示例

     

    public class TestThread implements Runnable{             public void run() {         throw new RuntimeException("throwing runtimeException.....");     }     }

    当线程代码抛出运行级别异常之后,线程会中断。主线程不受这个影响,不会处理这个,而且根本不能捕捉到这个异常,仍然继续执行自己的代码 (详细可以参照JDK DOC) 捕捉异常有两种方法,一种是把线程的错误捕捉到,往上抛 另一种则是通过线程池工厂,把异常捕捉到,uncaughtException往log4j写错误日志 方法一: public class TestMain { public static void main(String[] args) { try { TestThread t = new TestThread(); ExecutorService exec = Executors.newCachedThreadPool(); Future future = exec.submit(t); exec.shutdown(); future.get();//主要是这句话起了作用,调用get()方法,异常重抛出,包装在ExecutorException } catch (Exception e) { 这里可以把线程的异常继续抛出去 System.out.println("Exception Throw:" + e.getMessage()); } } } 方法二: public class HandlerThreadFactory implements ThreadFactory { public Thread newThread(Runnable runnable) { Thread t = new Thread(runnable); MyUncaughtExceptionHandler myUncaughtExceptionHandler = new MyUncaughtExceptionHandler(); t.setUncaughtExceptionHandler(myUncaughtExceptionHandler); return t; } } public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{ public void uncaughtException(Thread t, Throwable e) { System.out.println("write logger here:"+e); } } public class TestMain { public static void main(String[] args) { try { TestThread t = new TestThread(); ExecutorService exec = Executors.newCachedThreadPool(new HandlerThreadFactory()); exec.execute(t); } catch (Exception e) { System.out.println("Exception Throw:" + e.getMessage()); } } } 本人觉得方法一比较好用,而且简单

    最新回复(0)