2013-05-06 25 views
2

有在網絡上調用close()開放資源之前檢查null例子檢查。空與傳統finally塊用於關閉資源

final InputStream in = ...; // may throw IOException 
try { 
    // do something. 
} finally { 
    if (in != null) { // this is really required? 
     in.close(); 
    } 
} 

我一直都沒有做過null-checking-if

final InputStream in = ...; // may throw IOException 
try {     // when it reached to this line 'in' is never null, could it be? 
    // do something. 
} finally { 
    in.close(); // no null check required, am i wrong? 
} 
+2

如果你要「趕上」IOException,你應該把這個任務放在一個'try'塊中,不是嗎? – 2013-05-06 01:32:53

+0

@JinKwon什麼用的意思'...',它只是短打字或者是它在Java – 2017-01-17 12:36:46

回答

2

如果沒有資源成爲任何代碼執行路徑有零點需要對空支票null的機會。

你是做正確的事。

1
final InputStream in = ...; 

...可能會返回null,這就是爲什麼有一張支票。

+0

的關鍵詞是什麼用的'意思......',它只是短打字或在java中它是一個關鍵字 – 2017-01-17 12:37:23

1

的InputStream實現AutoClosable所以你可以使用一個try-with-resources聲明。那麼你不必像Java那樣爲你處理null。

try (InputStream in = ...) { 
    [some code] 
} 
+0

好的。伴侶! – 2018-01-27 06:44:32