Java的异常丢失
在某些特殊的方式使用finally子句时,会导致异常的丢失。如:
//: exceptions/LostMessage.java
// How an exception can be lost.
class VeryImportantException extends Exception {
public String toString() {
return "A very important exception!";
}
}
class HoHumException extends Exception {
public String toString() {
return "A trivial exception";
}
}
public class LostMessage {
void f() throws VeryImportantException {
throw new VeryImportantException();
}
void dispose() throws HoHumException {
throw new HoHumException();
}
public static void main(String[] args) {
try {
LostMessage lm = new LostMessage();
try {
lm.f();
} finally {
lm.dispose();
}
} catch(Exception e) {
System.out.println(e);
}
}
} /* Output:
A trivial exception
*///:~
更简单且容易出现的一种异常丢失情况就是,在finally块中使用了return,如下例子,在try块中虽然抛出了异常,但是它也不会产生任何输出。
package com.jacky.study.exception;
/**
* 异常丢失。当在finally中返回时,即使抛出了异常,它也不会产生任何输出。
*
* @author chenjie
* @times 2014-2-25 上午9:11:48
*
*/
public class ExceptionSilencer {
public static void main(String[] args) {
try {
throw new RuntimeException();
} finally {
return;
}
}
}