[優美的Java代碼之try...catch]
目錄- [優美的Java代碼之try...catch]
- 概述
- 優化
- 優化前寫法(JDK1.7之前)
- 優化后寫法(JDK1.7及以后)
- 延伸閱讀:嵌套的檔案流如何正確的關閉
概述
通常我們使用try...catch()捕獲例外時,如果遇到類似IO流的處理,要在finally部分關閉IO流,這是JDK1.7之前的寫法了;
在JDK7以后,可以使用優化后的try-with-resource陳述句,該陳述句確保了每個資源,在陳述句結束時關閉,所謂的資源是指在程式完成后,必須關閉的流物件,寫在()里面的流物件對應的類都實作了自動關閉介面AutoCloseable,
優化
語法:
try (創建流物件陳述句,如果多個,使用';'隔開) {
// 讀寫資料
} catch (IOException e) {
e.printStackTrace();
}
優化前寫法(JDK1.7之前)
Properties prop = new Properties();
File configFile = new File("/home/appconfig.properties");
FileInputStream fs = null;
InputStreamReader reader = null;
try {
fs = new FileInputStream(configFile);
reader = new InputStreamReader(fs, "utf-8");
prop.load(reader);
} catch (Exception e) {
Logger.error("load file error!!", e);
} finally {
try {
if (reader != null) {
reader.close();
}
if (fs != null) {
fs.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
優化后寫法(JDK1.7及以后)
try (FileInputStream fs = new FileInputStream(configFile); InputStreamReader reader = new InputStreamReader(fs, "utf-8")) {
prop.load(reader);
} catch (Exception e) {
Logger.error("load file error!!", e);
}
延伸閱讀:嵌套的檔案流如何正確的關閉
-
嵌套打開的流只需關閉最后打開的流,先打開的會自動關閉;
-
打開的流可以多次關閉不會出錯;
-
后面嘗試打開流時可能會發生例外,此時要考慮關閉前面已經打開的流,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/519262.html
標籤:其他
上一篇:JUC中的AQS底層詳細超詳解
下一篇:BigDecimal精度詳解
