2012-03-13 47 views
0

我想安全地關閉資源並傳播異常。到目前爲止,我提出了兩種解決方案。正確的方法來關閉文件並在同一時間傳播異常

解決方案1 ​​

FileObject sourceDir = null; 
FileObject targetDir = null; 
BufferedWriter bw = null; 
BufferedReader br = null; 

try { 
    // R/W operation with files 
} finally { 
    // close sourceDir, targetDir, br, bw 
} 

解決方案2

FileObject sourceDir = null; 
FileObject targetDir = null; 
BufferedWriter bw = null; 
BufferedReader br = null; 

try { 
    // R/W operation with files 
} catch (IOException e) { 
    throw e; 
} finally { 
    // close sourceDir, targetDir, br, bw 
} 

我不喜歡throw e在第二個解決方案,但try-finally似乎有些不尋常給我,讓我不確定我應該使用哪一個。或者有沒有更好的方法來做到這一點?

+1

您的解決方案2與解決方案1相同。只有在「catch」塊中添加更多代碼(例如,記錄異常)時,它纔會有所不同。 – 2012-03-13 11:01:30

+0

我知道,但再次拋出異常是不必要的一段代碼。在這種情況下,我不想在這裏登錄......我想知道如果嘗試終於可以。 – user219882 2012-03-13 11:13:51

+0

是的,它絕對沒問題。只是想你可能認爲這兩個代碼片段的行爲不同。 – 2012-03-13 11:19:53

回答

1

選項1非常正確。 try ... finally通常用於此。

您甚至可以將return放入try塊中,Java將處理finally並返回。

2

如果您想記錄異常並/或將其包含在運行時異常中並將其引發,那麼第二種解決方案可能很有用。

相關問題