当前位置: 代码迷 >> 综合 >> 从头认识java-10.6 finally(3)-异常的丢失
  详细解决方案

从头认识java-10.6 finally(3)-异常的丢失

热度:99   发布时间:2023-12-10 03:59:01.0

这一章节我们来讨论一下使用finally致使异常的丢失。

这个其实是非常偶然的错误,我们一般是不会犯的。

package com.ray.ch10;public class Test {public static void main(String[] args) throws Exception2 {try {throw new Exception1("Exception1");} finally {throw new Exception2("Exception2");}}
}class Exception1 extends Exception {public Exception1(String msg) {super(msg);}
}class Exception2 extends Exception {public Exception2(String msg) {super(msg);}
}

输出:

Exception in thread "main" com.ray.ch10.Exception2: Exception2
at com.ray.ch10.Test.main(Test.java:9)


从输出可以看出问题,Exception1完全不见了。


另一种更加简单的丢失。

package com.ray.ch10;public class Test {public static void main(String[] args) {try {throw new Exception();} finally {return;}}
}

输出:

(无)


总结:这一章节简单举例介绍使用finally致使异常的丢失,但是我们一般的使用都是try catch一起使用,那么就可以避免异常的丢失。


这一章节就到这里,谢谢。

-----------------------------------

目录