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.  

  • 相关阅读:
    常用DOS命令
    uCGUI窗口重绘代码分析
    STM32的FSMC总线驱动ili9341,掉电重启无法正常显示的问题
    再次编译 arm toolchains
    GDB和GDB Server
    QT Creator 环境使用 remote debug 调试 arm 程序
    [转]一个简洁的 systemd 操作指南
    用 bottle.py 写了个简单的升级包上传
    批量 ping 测试脚本(IP 扫描)
    float 对整形的取余运算
  • 原文地址:https://www.cnblogs.com/da-peng/p/10057003.html
Copyright © 2011-2022 走看看