1. 程式人生 > 其它 >32.自定義Java異常捕獲處理類及其使用

32.自定義Java異常捕獲處理類及其使用

  1. 自定義異常捕獲處理類
/**
 * <h1>異常捕捉</h1>
 * */
public class ExceptionHandler implements Thread.UncaughtExceptionHandler {

    @Override
    public void uncaughtException(Thread t, Throwable e) {

        StackTraceElement[] ses = e.getStackTrace();
        System.err.println("Exception in thread \"" + t.getName() + "\" " + e.toString());
		
        for (StackTraceElement se : ses) {
            System.err.println("\tat " + se);
        }
		
        Throwable ec = e.getCause();
        if (null != ec) {
            uncaughtException(t, ec);
        }
    }
}
  1. 使用異常捕獲處理類
/**
 * <h1>想辦法列印完整的異常棧資訊</h1>
 * */
public class CompleteException {

    private void imooc1() throws Exception {
        throw new Exception("imooc1 has exception...");
    }

    private void imooc2() throws Exception {

        try {
            imooc1();
        } catch (Exception ex) {
            throw new Exception("imooc2 has exception...", ex);
        }
    }

    private void imooc3() {
        try {
            imooc2();
        } catch (Exception ex) {
//            Throwable
            throw new RuntimeException("imooc3 has exception...", ex);
        }
    }

    public static void main(String[] args) {
            // 預設異常處理
//        try {
//            new CompleteException().imooc3();
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }

        // 使用自定義異常捕獲處理類,列印所有異常資訊
        Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
        new CompleteException().imooc3();
    }
}