首页 > 编程 > Java > 正文

java 异常链

2019-11-08 18:39:51
字体:
来源:转载
供稿:网友

使用异常链我们可以一层一层的去追溯错误的产生和传递,例如:

我在mian方法中调用method1方法,在method1方法中调用method2方法,在method2方法中抛出一个空指针异常。

public class Test { public static void main(String[] args) { Test t = new Test(); try { t.method1(); } catch (Exception e) { e.PRintStackTrace(); } } public void method1() throws Exception { try { method2(); } catch (Exception e) { Exception exception = new Exception("method1 exception"); exception.initCause(e); throw exception; //或者 //throw new Exception("method1 exception", e); } } public void method2() { throw new NullPointerException("method2 exception"); }}

打印如下:

java.lang.Exception: method1 exception at normal.Test.method1(Test.java:21) at normal.Test.main(Test.java:10)Caused by: java.lang.NullPointerException: method2 exception at normal.Test.method2(Test.java:30) at normal.Test.method1(Test.java:19) ... 1 more

可以看到 method1 exception,然后Caused by method2 exception。

之所以产生异常链,是因为

Exception exception = new Exception("method1 exception");exception.initCause(e);throw exception;//或者//throw new Exception("method1 exception", e);

如果不这样处理,打印如下:

java.lang.NullPointerException: method2 exception at normal.Test.method2(Test.java:31) at normal.Test.method1(Test.java:19) at normal.Test.main(Test.java:10)

这样就不能对整个过程的每一层进行处理了,只能看到产生异常的源头。


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表