The try-with-resources Statement

原文鏈接: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement.Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

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

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:

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

However, in this example, if the methods readLine and close both throw exceptions, then the method readFirstLineFromFileWithFinallyBlock throws the exception thrown from the finally block; the exception thrown from the try block is suppressed.

[ 然后,在這個例子中,如果 readLine 和 close 同時拋出異常赁项,然后 readFirstLineFromFileWithFinallyBlock 從 finally block 中拋出異常; 從 try block 拋出的異常就會被抑制. ]

In contrast, in the example readFirstLineFromFile, if exceptions are thrown from both the try block and the try-with-resources statement, then the method readFirstLineFromFile throws the exception thrown from the try block; the exception thrown from the try-with-resources block is suppressed.

[ 相反,在 readFirstLineFromFile 中,如果 try block 和 try-with-resources statement 同時拋出異常, 然后 readFirstLineFromFile 從 try block 拋出異常; 從 try-with-resources block 拋出的異常會被抑制. ]

In Java SE 7 and later, you can retrieve suppressed exceptions; see the section Suppressed Exceptions for more information.

[ 在 Java SE 7 之后,你可以 重新獲取 被抑制的異常; 詳見 Suppressed Exceptions. ]

You may declare one or more resources in a try-with-resources statement. The following example retrieves the names of the files packaged in the zip file zipFileName and creates a text file that contains the names of these files:

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

In this example, the try-with-resources statement contains two declarations that are separated by a semicolon: ZipFile and BufferedWriter. When the block of code that directly follows it terminates, either normally or because of an exception, the close methods of the BufferedWriter and ZipFile objects are automatically called in this order. Note that the close methods of resources are called in the opposite order of their creation.

[
try-with-resources statement 可以包含多個資源蛾洛,當(dāng) block code 正常或異常退出時饭庞,close 方法會被自動調(diào)用戒悠,只是順序和創(chuàng)建該資源時的順序相反。
]

The following example uses a try-with-resources statement to automatically close a java.sql.Statement object:

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

The resource java.sql.Statement used in this example is part of the JDBC 4.1 and later API.

Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

Note: 一個 try-with-resources statement 可以有 catch 和 finally blocks,就像一個普通的 try statement. 在一個 try-with-resources statement, 任何 catch 或 finally block 在 聲明的資源被關(guān)閉后 運行.

  • Suppressed Exceptions[異常抑制]

An exception can be thrown from the block of code associated with the try-with-resources statement. In the example writeToFileZipFileContents, an exception can be thrown from the try block, and up to two exceptions can be thrown from the try-with-resources statement when it tries to close the ZipFile and BufferedWriter objects. If an exception is thrown from the try block and one or more exceptions are thrown from the try-with-resources statement, then those exceptions thrown from the try-with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown by the writeToFileZipFileContents method. You can retrieve these suppressed exceptions by calling the Throwable.getSuppressed method from the exception thrown by the try block.

Classes That Implement the AutoCloseable or Closeable Interface
See the Javadoc of the AutoCloseable and Closeable interfaces for a list of classes that implement either of these interfaces. The Closeable interface extends the AutoCloseable interface. The close method of the Closeable interface throws exceptions of type IOException while the close method of the AutoCloseable interface throws exceptions of type Exception. Consequently, subclasses of the AutoCloseable interface can override this behavior of the close method to throw specialized exceptions, such as IOException, or no exception at all.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末舟山,一起剝皮案震驚了整個濱河市绸狐,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌累盗,老刑警劉巖寒矿,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異若债,居然都是意外死亡符相,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門蠢琳,熙熙樓的掌柜王于貴愁眉苦臉地迎上來啊终,“玉大人,你說我怎么就攤上這事傲须±渡” “怎么了?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵泰讽,是天一觀的道長例衍。 經(jīng)常有香客問我昔期,道長,這世上最難降的妖魔是什么肄渗? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任镇眷,我火速辦了婚禮蟹演,結(jié)果婚禮上妙同,老公的妹妹穿的比我還像新娘姐帚。我一直安慰自己琐驴,他們只是感情好镣奋,可當(dāng)我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布侍筛。 她就那樣靜靜地躺著钞脂,像睡著了一般纵散。 火紅的嫁衣襯著肌膚如雪圈驼。 梳的紋絲不亂的頭發(fā)上人芽,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天,我揣著相機與錄音绩脆,去河邊找鬼萤厅。 笑死,一個胖子當(dāng)著我的面吹牛靴迫,可吹牛的內(nèi)容都是我干的惕味。 我是一名探鬼主播,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼玉锌,長吁一口氣:“原來是場噩夢啊……” “哼名挥!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起主守,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤禀倔,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后参淫,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體救湖,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年涎才,在試婚紗的時候發(fā)現(xiàn)自己被綠了捎谨。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡憔维,死狀恐怖涛救,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情业扒,我是刑警寧澤检吆,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站程储,受9級特大地震影響蹭沛,放射性物質(zhì)發(fā)生泄漏臂寝。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一摊灭、第九天 我趴在偏房一處隱蔽的房頂上張望咆贬。 院中可真熱鬧,春花似錦帚呼、人聲如沸掏缎。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽眷蜈。三九已至,卻和暖如春沈自,著一層夾襖步出監(jiān)牢的瞬間酌儒,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工枯途, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留忌怎,地道東北人。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓酪夷,卻偏偏與公主長得像呆躲,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子捶索,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,979評論 2 355

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,332評論 0 10
  • 16年過年時候跟一些朋友一樣立了個flag.點贊讀書的小游戲。 當(dāng)時覺得如果能挑戰(zhàn)一下自己的樂趣灰瞻,那么如...
    普萘洛爾Sakura閱讀 350評論 0 2