32.自定义Java异常捕获处理类及其使用


  1. 自定义异常捕获处理类
/**
 * 

异常捕捉

* */ 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. 使用异常捕获处理类
/**
 * 

想办法打印完整的异常栈信息

* */ 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(); } }