异常可能会丢失 java异常处理机制的一个缺陷
//: 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) throws Exception {
LostMessage lm = new LostMessage();
try {
lm.f();
}
/*catch (Exception e)// 必须用catch 明显的捕获 不能期望像下面dispose()一样调用方法时 异常自己打印出
// 栈内异常信息,因为finally得缘故 f()的异常会被丢失!!
{
e.printStackTrace();
}
*/
finally {
lm.dispose();
}
}
}
No.9 丢失异常
最新推荐文章于 2022-04-19 11:57:20 发布