Java的异常实现也有瑕疵,用某些特殊的方式使用finally子句,就会发生这种情况:
代码:
1 public class ExceptionLost {
2 /**
3 * @param args
4 */
5 public static void main(String[] args) {
6 try {
7 ExceptionLost exLost = new ExceptionLost();
8 try {
9 exLost.throwV();
10 } finally {
11 exLost.dispose();
12 }
13 } catch (Exception e) {
14 System.out.println(e);
15 }
16 }
17
18 public void throwV() throws VeryImportantException {
19 throw new VeryImportantException();
20 }
21
22 public void dispose() throws HoHumException {
23 throw new HoHumException();
24 }
25 }
26
27 class VeryImportantException extends Exception {
28 public String toString() {
29 return "A very Important exception!";
30 }
31 }
32
33 class HoHumException extends Exception {
34 public String toString() {
35 return "A trivial exception";
36 }
37 }
结果:A trivial exception
结论:从输出中可以看到VeryImportantException不见了,它被finally子句的HoHumException所取代。事实上如果从finally子句直接返
也会丢失异常。
Ps: 具体内容看Thanking in Java第四版268页。