<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                企業??AI智能體構建引擎,智能編排和調試,一鍵部署,支持知識庫和私有化部署方案 廣告
                # Java `try-with-resources` > 原文: [https://www.programiz.com/java-programming/try-with-resources](https://www.programiz.com/java-programming/try-with-resources) #### 在本教程中,我們將學習`try-with-resources`語句以自動關閉資源。 `try-with-resources`語句在語句末尾自動關閉所有資源。 資源是程序結束時要關閉的對象。 其語法為: ```java try (resource declaration) { // use of the resource } catch (ExceptionType e1) { // catch block } ``` 從上面的語法可以看出,我們通過以下方式聲明`try-with-resources`語句: 1. 在`try`子句中聲明和實例化資源。 2. 指定并處理關閉資源時可能引發的所有異常。 **注意**: `try-with-resources`語句關閉實現[`AutoCloseable`接口](https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html)的所有資源。 * * * 讓我們以實現`try-with-resources`語句的示例為例。 ### 示例 1:`try-with-resources` ```java import java.io.*; class Main { public static void main(String[] args) { String line; try(BufferedReader br = new BufferedReader(new FileReader("test.txt"))) { while ((line = br.readLine()) != null) { System.out.println("Line =>"+line); } } catch (IOException e) { System.out.println("IOException in try block =>" + e.getMessage()); } } } ``` **如果未找到`test.txt`文件,則輸出。** ```java IOException in try-with-resources block =>test.txt (No such file or directory) ``` **如果找到`test.txt`文件,則輸出。** ```java Entering try-with-resources block Line =>test line ``` 在此示例中,我們使用`BufferedReader`的實例從`test.txt`文件中讀取數據。 在`try-with-resources`語句中聲明并實例化`BufferedReader`可以確保無論`try`語句正常完成還是引發異常,都關閉其實例。 如果發生異常,則可以使用異常處理塊或[`throws`關鍵字](https://www.programiz.com/java-programming/throw-throws)進行處理。 * * * ## 抑制的異常 在上面的示例中,在以下情況下,可以從`try-with-resources`語句引發異常: * 找不到文件`test.txt`。 * 關閉`BufferedReader`對象。 也可能從`try`塊引發異常,因為文件讀取可能隨時因多種原因而失敗。 如果從`try`塊和`try-with-resources`語句都引發了異常,則將引發`try`塊的異常并抑制來自`try-with-resources`語句的異常。 ### 檢索抑制的異常 在 Java 7 和更高版本中,可以通過從`try`塊引發的異常中調用`Throwable.getSuppressed()`方法來檢索受抑制的異常。 此方法返回所有抑制的異常的數組。 我們在`catch`塊中獲得了抑制的異常。 ```java catch(IOException e) { System.out.println("Thrown exception=>" + e.getMessage()); Throwable[] suppressedExceptions = e.getSuppressed(); for (int i=0; i<suppressedExceptions.length; i++) { System.out.println("Suppressed exception=>" + suppressedExceptions[i]); } } ``` * * * ## 使用`try-with-resources`的優勢 這是使用`try-with-resources`的優點: ### 1.`finally`塊不需要關閉資源 在 Java 7 引入此功能之前,我們必須使用`finally`塊來確保關閉資源以避免資源泄漏。 這是一個類似于**示例 1** 的程序。 但是,在此程序中,我們使用了`finally`塊來關閉資源。 ### 示例 2:使用`finally`塊關閉資源 ```java import java.io.*; class Main { public static void main(String[] args) { BufferedReader br = null; String line; try { System.out.println("Entering try block"); br = new BufferedReader(new FileReader("test.txt")); while ((line = br.readLine()) != null) { System.out.println("Line =>"+line); } } catch (IOException e) { System.out.println("IOException in try block =>" + e.getMessage()); } finally { System.out.println("Entering finally block"); try { if (br != null) { br.close(); } } catch (IOException e) { System.out.println("IOException in finally block =>"+e.getMessage()); } } } } ``` **輸出** ```java Entering try block Line =>line from test.txt file Entering finally block ``` 從上面的示例可以看出,使用`finally`塊來清理資源使代碼更加復雜。 注意`finally`塊中的`try...catch`塊嗎? 這是因為在關閉`finally`塊內的`BufferedReader`實例時也會出現`IOException`,因此也將其捕獲并處理。 `try-with-resources`語句執行**自動資源管理**。 我們不需要顯式關閉資源,因為 JVM 會自動關閉它們。 這使代碼更具可讀性,更易于編寫。 * * * ### 2.`try-with-resources`和多種資源 我們可以用分號`;`分隔`try-with-resources`語句中的多個資源 ### 示例 3:`try-with-resources`和多種資源 ```java import java.io.*; import java.util.*; class Main { public static void main(String[] args) throws IOException{ try (Scanner scanner = new Scanner(new File("testRead.txt")); PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) { while (scanner.hasNext()) { writer.print(scanner.nextLine()); } } } } ``` 如果執行該程序時未生成任何異常,則`Scanner`對象將從`testRead.txt`文件中讀取一行并將其寫入新的`testWrite.txt`文件中。 進行多個聲明時,`try-with-resources`語句以相反的順序關閉這些資源。 在此示例中,首先關閉`PrintWriter`對象,然后關閉`Scanner`對象。 * * * ## Java 9 `try-with-resources`增強 在 Java 7 中,`try-with-resources`語句受到限制。 該資源需要在其塊內本地聲明。 ```java try (Scanner scanner = new Scanner(new File("testRead.txt"))) { // code } ``` 如果我們在 Java 7 中在塊外聲明資源,則將生成一條錯誤消息。 ```java Scanner scanner = new Scanner(new File("testRead.txt")); try (scanner) { // code } ``` 為了解決此錯誤,Java 9 改進了`try-with-resources`語句,以便即使未在本地聲明資源引用也可以使用。 上面的代碼現在將執行,沒有任何編譯錯誤。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看