下面的例子是一个不安全的异常处理,在catch和finally块中抛出的异常,可能隐藏了其他的异常

  InputStream input = null;
  try{

    input = new FileInputStream("myFile.txt");

    //do something with the stream

  } catch(IOException e){
    throw new WrapperException(e);
  } finally {
    try{
     input.close();
    } catch(IOException e){
       throw new WrapperException(e);
    }
  }

如果 FileInputStream构造函数中抛了一个 FileNotFoundException,首先catch块将执行. 抛出一个包装异常 WrapperException。然后,在finally块中会执行关闭流的操作。然而,由于FileNotFoundException是在FileInputStream构造函数中抛出的,所以input引用将会是null,在执行input.close()时会抛出NPE(NullPointerException),NullPointerException并不能被catch块(IOException e) 捕获,因此WrapperException将会丢失。

results matching ""

    No results matching ""