UncaughtExceptionHandler:java未捕获的异常/错误默认处理方式

UncaughtExceptionHandler:java未捕获的异常/错误

@(JAVA)[java]

java有一部分异常属于运行时异常,这类异常发生时通过会导致程序发生错误,导致退出。如数据下标过大,内存不足等。

对于这类异常,默认的情况是打印相关的错误stack,然后退出程序。但这对于用户而言十分不友好;另外,有可以发生异常或者错误时不希望程序退出。

此时可以为线程添加一个默认的异常处理器。

主要使用

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(Thread thread, Throwable thrown) {
    .....
    }
}

来处理未捕获的异常。也可以使用setUncaughtExceptionHandler,但这只对当前线程生效,default的话默认对所有线程生效。

另注意,Error和Exception 都实现了Throwable,而它们之间没有直接关系

public class UncaughtExceptionHandlerDemo {
    private static Logger LOG = LoggerFactory.getLogger(UncaughtExceptionHandlerDemo.class);

    public static void main(String[] args) {

        setupDefaultUncaughtExceptionHandler();
        //NO argument pass to main, so ArrayIndexOutOfBoundsException will occur.
        System.out.println(args[1]);
    }

    public static void setupDefaultUncaughtExceptionHandler() {
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                public void uncaughtException(Thread thread, Throwable thrown) {
                    try {
                        handleUncaughtException(thrown);
                    } catch (Error err) {
                       // LOG.error("Received error in main thread.. terminating server...", err);
                        System.err.println("Received error in main thread.. terminating server..." + err);
                        Runtime.getRuntime().exit(-2);
                    }catch(Exception e){
                        System.err.println("Exception happen. Cause:  " + e.getMessage());
                        e.printStackTrace();
                    }
                }
            });
    }


    public static void handleUncaughtException(Throwable t) throws Exception {
        if (t != null && t instanceof Error) {
            if (t instanceof OutOfMemoryError) {
                try {
                    System.err.println("Halting due to Out Of Memory Error..." + Thread.currentThread().getName());
                } catch (Throwable err) {
                    //Again we don't want to exit because of logging issues.
                }
                Runtime.getRuntime().halt(-1);
            } else {
                //Running in daemon mode, we would pass Error to calling thread.
                throw (Error) t;
            }
        }else{
            throw (Exception) t;
        }

    }

}

你可能感兴趣的:(1.6.1,JAVA)