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

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

一、【try资源句式】是干嘛用的?
在JDK 7版本中出现了一种新的句式: try(资源)

try资源 (try with resources) 句式是一个 try 句式,可以 try 一个或多个资源。
资源必须在用完后 close 掉。使用try资源句式可以自动 close 资源。

任何实现了 java.lang.AutoCloseable 接口的类
都可以使用 try资源句式,自动 close。
public interface java.io.Closeable extends java.lang.AutoCloseable

一句话:
使用 try资源句式 用来自动 close 资源。而不用担心资源一直占用内存无法释放。


二、使用语法 - 何时自动关闭资源
下面的例子用于读取文件的第一行。它使用一个 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 接口,
它将被自动关闭,无论是程序正常结束还是中途抛出异常。


三、异常是如何被抛出/捕获的?

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);
    }
}



四、可以 try 多个资源

使用 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());
        }
    }
}



五、获取被 try资源句式 忽略的异常

前述已讲过,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




-

猜你喜欢

转载自lixh1986.iteye.com/blog/2370408