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.  

  • 相关阅读:
    10.22(day11) Object类 异常
    10.19(day10)
    10.18(day9)内部类 抽象类 接口
    10.17(day8) Static关键字 包的使用 访问修饰符的权限 设计模式
    paho-mqtt error1: incorrect protocol version解决方法
    Python进阶-pickle/eval/exec
    关联分析算法Apriori和FP-Growth
    LOF聚类分析
    Python进阶-迭代器和生成器
    Linux常见坑
  • 原文地址:https://www.cnblogs.com/da-peng/p/10057003.html
Copyright © 2011-2022 走看看