封装异常处理之坑
public static void main(String []f) { try { test(); } catch (Exception e) { e.printStackTrace(); } } private static void test() { try { int i = 1 / 0; } catch (Exception e) { throw new RuntimeException("hh"); } }
java.lang.RuntimeException: hh msg遗失
at com.xxx.config.exception.DBException.test(DBException.java:39) 第一堆栈:throw new RuntimeException("hh");遗失了第一现场
at com.xxx.config.exception.DBException.main(DBException.java:29)
小结:msg遗失,堆栈第一现场遗失
项目中做了修复:
-===========================================
private static void test() { try { int i = 1 / 0; } catch (Exception e) { throw new RuntimeException("hh", e); } }
java.lang.RuntimeException: hh
at com.xxx.config.exception.DBException.test(DBException.java:39) 第一堆栈仍然是throw new RuntimeException("hh")
at com.xxx.config.exception.DBException.main(DBException.java:29)
Caused by: java.lang.ArithmeticException: / by zero
at com.xxx.config.exception.DBException.test(DBException.java:37) 好在第一现场出现在Caused By中,但莫名其妙堆栈变长了,不利于查看
... 1 more
msg遗失,但仍可在Caused By中,找到堆栈第一现场
private static void test() { try { int i = 1 / 0; } catch (Exception e) { throw e; } }
java.lang.ArithmeticException: / by zero
at com.xxx.config.exception.DBException.test(DBException.java:37) 第一堆栈为1/0
at com.xxx.config.exception.DBException.main(DBException.java:29)
msg原汁原味,堆栈第一现场在第一行
实践中
1)优先直接抛原始异常
2)若就是需要封装原始异常,务必将原始异常e传入封装异常,否则遭到堆栈第一现场遗失