[英]Handle exception without try/catch
我有一個方法,拋出的異常必須由調用方處理,而不是由方法本身處理(簽名中指定的異常,而不是主體中指定的異常)。 但是,如果發生了一些不好的情況,我想在調用者不得不處理該問題之前,使用類似於finally
語句的方法來關閉我的閱讀器。
在當前配置中,如果觸發了異常,則讀取器保持打開狀態。
private static void executeFile(Connection c, String fileName) throws SQLException, IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), Charset.defaultCharset())); // $JL-I18N$
/*
Lot of stuff happen here, and might trigger exceptions
*/
reader.close();
}
有沒有辦法處理這種情況? 還是應該重構該方法以單獨處理異常?
編輯
評論中提供了一些很好的技巧。 我最終選擇考慮的解決方案是提取觸發警告的代碼並使用try-with-resources。
這就是你的做法。 使用try-with-resources。
private static void executeFile(Connection c, String fileName)
throws SQLException, IOException {
try (InputStream is = new FileInputStream(fileName);
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr)) {
/* Lots of stuff */
}
}
在try塊中引發的異常將被傳播,並且閱讀器堆棧將被關閉。 如果(假設)由try-with-resource執行的隱式close()
拋出異常:
注意,我已經重寫了`
new InputStreamReader(is, Charset.defaultCharset())
如
new InputStreamReader(is)
因為它們是等效的:請檢查javadoc。 另一個重寫只是為了提高可讀性,盡管它確實說明了“嘗試使用資源”可以管理多個資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.