Java之Java7新特性之try資源句式

[color=green][size=medium][b]Java之Java7新特性之try資源句式[/b][/size][/color]

[size=medium][b]一、【try資源句式】是幹嘛用的?[/b][/size]
在JDK 7版本中出現了一種新的句式: try(資源)

try資源 (try with resources) 句式是一個 try 句式,可以 try 一個或多個資源。
資源必須在用完後 close 掉。使用try資源句式可以自動 close 資源。

[b]任何實現了 java.lang.AutoCloseable 接口的類[/b],
都可以使用 try資源句式,自動 close。

public interface java.io.Closeable extends java.lang.AutoCloseable

一句話:
使用 try資源句式 用來自動 close 資源。而不用擔心資源一直佔用內存無法釋放。


[size=medium][b]二、使用語法 - 何時自動關閉資源[/b][/size]
下面的例子用於讀取文件的第一行。它使用一個 BufferedReader 的實例來讀取數據。
BufferedReader 在這裏就是一個資源,它必須在程序運行結束後被關閉。

static String readFirstLineFromFile(String path) throws IOException {
try(
BufferedReader br = new BufferedReader(new FileReader(path))
){
return br.readLine();
}
}

BufferedReader 在 jdk1.7 中實現了 java.lang.AutoCloseable 接口,
它將被自動關閉,無論是程序正常結束還是中途拋出異常。


[size=medium][b]三、異常是如何被拋出/捕獲的?[/b][/size]

try資源句式 其功能是用於資源的自動關閉,而對於異常的 catch 和 finally,
在寫法上跟 jkd 1.7 之前沒有區別。

在 jdk 1.7 之前,如果遇到異常,會寫在 catch 中,然後在 finally 塊中關閉資源。

static String readFirstLineFromFileWithFinallyBlock(String path)
throws IOException {
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
}

上例中如果 readLine() 和 close() 都拋出異常時,該方法拋出的異常是 finally 塊中的異常,
try塊中的異常被忽略了。


與之相反的是,try資源句式 則會拋出try塊中的異常,try句式中的異常被忽略掉了。
當然你仍然可以在 catch() 塊中獲取到被忽略的異常。

public static void viewTable(Connection con) throws SQLException {

String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";

try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery(query);

while (rs.next()) {
String coffeeName = rs.getString("COF_NAME");
int supplierID = rs.getInt("SUP_ID");
float price = rs.getFloat("PRICE");
int sales = rs.getInt("SALES");
int total = rs.getInt("TOTAL");

System.out.println(coffeeName + ", " + supplierID + ", " +
price + ", " + sales + ", " + total);
}
} catch (SQLException e) {
JDBCTutorialUtilities.printSQLException(e);
}
}



[size=medium][b]四、可以 try 多個資源[/b][/size]

使用 try資源句式 時,可以將多個資源寫在一起,中間用分號隔開。
注意:
1、最後一個資源後面沒有分號。
2、資源的關閉順序跟寫的順序相反(最先打開的最後關閉)。

public static void writeToFileZipFileContents(String zipFileName,
String outputFileName)
throws java.io.IOException {

java.nio.charset.Charset charset =
java.nio.charset.StandardCharsets.US_ASCII;
java.nio.file.Path outputFilePath =
java.nio.file.Paths.get(outputFileName);

// Open zip file and create output file with
// try-with-resources statement

try (
java.util.zip.ZipFile zf =
new java.util.zip.ZipFile(zipFileName);
java.io.BufferedWriter writer =
java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
) {
// Enumerate each entry
for (java.util.Enumeration entries =
zf.entries(); entries.hasMoreElements();) {
// Get the entry name and write it to the output file
String newLine = System.getProperty("line.separator");
String zipEntryName =
((java.util.zip.ZipEntry)entries.nextElement()).getName() +
newLine;
writer.write(zipEntryName, 0, zipEntryName.length());
}
}
}



[size=medium][b]五、獲取被 try資源句式 忽略的異常[/b][/size]

前述已講過,try{} 體中的異常會覆蓋掉 try() 表達式中的異常。
但仍然可以通過 try{} 體中拋出的異常 和 Throwable.getSuppressed() 方法獲取那些被忽略的異常。


-
轉載請註明,
原文出處:http://lixh1986.iteye.com/blog/2370408


引用:

The try-with-resources Statement
https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html


-
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章