exceptions - Pitfall: the Lost Exception

探讨Java中异常处理的潜在问题,特别是在finally子句中抛出异常可能导致的重要异常丢失现象,及如何使用return语句静默异常。

Unfortunately, there’s a flaw in Java’s exception implementation. Although exceptions are an indication of a crisis in your program and should never be ignored, it’s possible for an exception to be lost. 

// exceptions/LostMessage.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// How an exception can be lost

class VeryImportantException extends Exception {
  @Override
  public String toString() {
    return "A very important exception!";
  }
}

class HoHumException extends Exception {
  @Override
  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 (VeryImportantException | HoHumException e) {
      System.out.println(e);
    }
  }
}
/* Output:
A trivial exception
*/

The output shows no evidence of the VeryImportantException, which is replaced by the HoHumException in the finally clause. This is a rather serious pitfall, since it means an exception can be completely lost, and in a far more subtle and difficult-to-detect fashion than the preceding example. In contrast, C++ treats the situation where a second exception is thrown before the first one is handled as a dire programming error.

 

return from inside a finally clause:

// exceptions/ExceptionSilencer.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

public class ExceptionSilencer {
  public static void main(String[] args) {
    try {
      throw new RuntimeException();
    } finally {
      // Using 'return' inside the finally block
      // will silence any thrown exception.
      return;
    }
  }
}

references:

1. On Java 8 - Bruce Eckel

2.  https://github.com/wangbingfeng/OnJava8-Examples/blob/master/exceptions/LostMessage.java

3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/exceptions/ExceptionSilencer.java

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值