zoukankan      html  css  js  c++  java
  • JAVA线程全局异常处理

      大家平时写线程很多,但可能很少关注如何捕获线程的全局异常。其实jdk提供了两种捕获全局异常的方法,一种是基于整个线程类(staticsetDefaultUnaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)),一种基于线程的一个对象(setUncaughtExceptionHandler(Thread.UncaughtExceptionHander eh))。

      下面是基于线程的一个对象的示例:

      

    /**
     * 主线程
     */
    public class MainThread extends Thread implements Thread.UncaughtExceptionHandler {
    
        public static void main(String[] args){
            new MainThread().start();
        }
    
        public void run(){
            ChildThread child=new ChildThread();
            child.setUncaughtExceptionHandler(this);
            child.start();
        }
    
        /**
         * 获得子线程异常
         * @param t
         * @param e
         */
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.out.println("以下为子线程异常:");
            e.printStackTrace();
        }
    }
    /**
     * 子线程
     */
    public class ChildThread extends Thread{
    
        public void run(){
            int a=Integer.parseInt("sdfdf");
        }
    }

    执行主线程的main方法启动子线程,此时主线程uncaughtException会捕获子线程的异常,执行结果如下:

    以下为子线程异常:
    java.lang.NumberFormatException: For input string: "sdfdf"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.lang.Integer.parseInt(Integer.java:492)
        at java.lang.Integer.parseInt(Integer.java:527)
        at net.hsh.util.ChildThread.run(ChildThread.java:9)
  • 相关阅读:
    HDU 4912 Paths on the tree(LCA+贪心)
    BZOJ 1044 木棍分割(二分答案 + DP优化)
    Codeforces 551E GukiZ and GukiZiana(分块思想)
    计蒜客 UCloud 的安全秘钥(随机化+Hash)
    HDU 5794 A Simple Chess(杨辉三角+容斥原理+Lucas定理)
    mac-profile
    mac-httpd
    launchctl
    brew
    操作系统
  • 原文地址:https://www.cnblogs.com/myzhijie/p/4835638.html
Copyright © 2011-2022 走看看