2013年7月20日 星期六

Java IO: Exception Handling - 不安全的IO Exception處理

參考:Fail Safe Exception Handling

其實這篇等於是把參考文章直接以自己說法再寫一次當作心得筆記,想看詳細的話看上述參考文章比較妥當


處理IO時常常發生個惱人的問題,假設下列code:
 
public class WrapperException extends Exception {

 public WrapperException(IOException e) {
  super(e);
 }
}

 
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);
    }
  }

假設"myFile.txt"這個檔案並不存在,那麼上述Code執行如下:

  1. throw java.io.FileNotFoundException() (at FileInputStream() constructor)
  2. catch(IOException e) block,rethrow WrapperException
  3. finally block
  4. 由於input未初始化成功,因此再次被finally中的try catch捕捉,然而這次拋出的為NullPointerException
因此上述的exception顯示如下:

Exception in thread "main" java.lang.NullPointerException
 at exception.FailSaveException.failSave(FailSaveException.java:30)
 at exception.FailSaveException.main(FailSaveException.java:15)

原先造成exception的始祖,最該被拋出的FileNotFoundException()就這樣默默的被吃掉了....
解決方式是:在finally的input.clode中加入null check:
if(input != null) 
   input.close();

然而讓我們假設另一個情況:
  假設檔案存在,input順利被建立,但在try catch中處理內容時因為某些原因再度造成io exception,此時順序會變為:

  1. throw some IOException in first try catch block
  2. first try catch catch it ,rethrow WrapperException
  3. finally block
  4. rethrow WrapperException again.....if input.close() also error
然而要是執行到步驟3時,input.close()又再次因為某些不知明原因,再度throw IOException,則就會多了步驟4,再一次的,最關鍵的始祖IOException又被吃掉(步驟1)!!
(上述假設無example code,推測是因為很難馬上弄出個簡單的input.close()也出問題的範例)
而為了解決上述問題,讓我們這些苦命developer可以在第一時間就發現始祖exception,Java 7帶來了一個叫 try-with resource的機制。

詳情請見下篇介紹XD

1 則留言:

  1. It is such an amazing write-up; since I started working as a freelancer, I also noticed that projects and freelancers could not communicate due to a lack of a reliable, secure, and specified platform. I was quite fortunate here. I got one of the wonderful platforms for the same, which is Eiliana.com. Many clients actively look to Hire a programmer designated for specific projects. I am quite happy now.

    回覆刪除