zoukankan      html  css  js  c++  java
  • 多线程抓取异常

    下面这段代码  可以看出  run方法里面会抛出一个异常、我们在主方法里面进行抓取、但是大家可以复制去测试、这个抓取异常中的代码不会运行

    也就是没有抓取到、

    在线程里面的异常主程序是无法抓取的、

        public static void main(String[] args) {
            try {
                T01 t01 = new T01();
                t01.start();
            } catch (Exception e) {
                System.out.println(1);
            }
            
        }
        
    
    }
    class T01 extends Thread{
        
        @Override
        public void run() {        
                System.out.println(1/0);        
           }
        }

    但是线程提供了抓取异常的方法

    以下这个方法就可以在线程发生异常的时候抓取到、放在线程启动之前

     public static void main(String[] args) {
            try {
                T01 t01 = new T01();
               t01.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {            
                    @Override
                    public void uncaughtException(Thread t, Throwable e) {
                      System.out.println(t.getName());
                      System.out.println(e.getMessage());                    
                    }
                });
                t01.start();
            } catch (Exception e) {
                System.out.println(1);
            }
            
        }
        
    
    }
    class T01 extends Thread{
        
        @Override
        public void run() {
            
                System.out.println(1/0);
        
            
           }
        }
  • 相关阅读:
    Girls and Boys
    Kindergarten
    codevs 2822 爱在心中
    Popular Cows
    QWQ
    2488 绿豆蛙的归宿(拓扑+dp)
    P1119 灾后重建
    Mr. Frog’s Game
    Basic Data Structure
    A strange lift
  • 原文地址:https://www.cnblogs.com/qq376324789/p/10481671.html
Copyright © 2011-2022 走看看