zoukankan      html  css  js  c++  java
  • 处理非正常终止的错误

    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.  

  • 相关阅读:
    软件测试学习-计算机基础知识
    《剑指offer》— JavaScript(4)重建二叉树
    《剑指offer》— JavaScript(3)从尾到头打印链表
    《剑指offer》— JavaScript(1)二维数组中的查找
    《剑指offer》— JavaScript(2)替换空格
    React学习笔记
    dislpay:flex布局
    JavaScript异步编程的方法
    test of CMSoft
    全局对象和全局函数
  • 原文地址:https://www.cnblogs.com/da-peng/p/10057003.html
Copyright © 2011-2022 走看看