异常的嵌套在spring开发中经常遇到。 例如,在页500中,如果观察控制台,就会发现连续发生了几个异常。 从逻辑上讲,在一般开发中发生一个异常直接抛出的话,只会打印该异常发生的原因。 查看Exception类的源代码后,可以使用某种构建方法,exception(stringmsg,Throwable e ); 该方法的注释翻译为constructsanewexceptionwiththespecifieddetailmessageandcause .基于指定的详细信息和原因构建新异常。
下面的代码在try块中创建三个异常,第二个异常包含第一个异常,第三个异常包含第二个异常并抛出,catch块中包含另一个运行时异常,第三个异常包含第三个异常。
公共类nest exception {
publicstaticvoidmain (字符串[ ] args ) {
创建表达式(;
}
publicstaticvoidcreateexception (
try {
runtimeexceptionnullpointerexception=newruntimeexception (空指针异常1 );
runtimeexceptionnullpointerexception2=newruntimeexception (' nullpointerexception );
runtimeexceptionnullpointerexception3=newruntimeexception (' nullpointerexception2);
throw nullPointerException3;
}catch(exceptione ) {
throw new RuntimeException (“动作异常”,e );
}
}
}
运行main方法可显示控制台的打印信息
exceptioninthread ' main ' Java.lang.runtime exception 3360操作异常
atcom.wyk.JDK.exception.nest exception.create exception (nest exception.Java :16 ) )。
atcom.wyk.JDK.exception.nest exception.main (nest exception.Java :6 ) )。
caused by : Java.lang.runtime exception :空指针异常3
atcom.wyk.JDK.exception.nest exception.create exception (nest exception.Java :13 ) )。
. 1模式
caused by : Java.lang.runtime exception :空指针异常2
atcom.wyk.JDK.exception.nest exception.create exception (nest exception.Java :12 ) )。
. 1模式
caused by : Java.lang.runtime exception :空指针异常1
atcom.wyk.JDK.exception.nest exception.create exception (nest exception.Java 336011 ) )。
. 1模式
因为main方法没有处理异常,所以异常会被抛到更高层。 最后,输出了所有嵌套的异常消息。 从这个小程序中可以看到异常的嵌套作用
再看一个吞噬异常的程序
公共类nest exception {
publicstaticvoidmain (字符串[ ] args ) {
创建表达式(;
}
publicstaticvoidcreateexception (
try {
runtimeexceptionnullpointerexception=newruntimeexception (空指针异常1 );
runtimeexceptionnullpointerexception2=newruntimeexception (' nullpointerexception );
runtimeexceptionnullpointerexception3=newruntimeexception (' nullpointerexception2);
throw nullPointerException3;
}catch(exceptione ) {
throw new RuntimeException (“运行异常”,e );
}finally{
throw new RuntimeException ('执行异常2 );
}
}
}
输出结果是
exceptioninthread ' main ' Java.lang.runtime exception 3360动作异常3
atcom.wyk.JDK.exception.nest exception.create exception (nest exception.Java :18 ) )。
atcom.wyk.JDK.exception.nest exception.main (nest exception.Java :6 ) )。
程序只抛出了执行异常2异常。 也就是说,最好不要在finally块中使用return或throw这样的关键字。 发生异常时会吞噬之前的异常信息,到时候就不知道是什么原因了。