<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>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # Java 異常處理 > 原文: [https://www.programiz.com/java-programming/exception-handling](https://www.programiz.com/java-programming/exception-handling) #### 在本教程中,您將借助示例學習使用 Java 處理異常。 為了處理異常,我們將使用`try...catch...finally` 塊。 在上一教程中,我們了解了異常。 異常是程序執行期間發生的意外事件。 * * * ## 捕捉和處理異常 在 Java 中,我們使用異常處理器組件`try`,`catch`和`finally`塊來處理異常。 為了捕獲和處理異常,我們將`try...catch...finally`塊放置在可能生成異常的代碼周圍。`finally`塊是可選的。 `try...catch...finally`的語法為: ```java try { // code } catch (ExceptionType e) { // catch block } finally { // finally block } ``` * * * ## Java `try...catch`塊 可能產生異常的代碼位于`try`塊中。 每個`try`塊后應緊跟`catch`或`finally`塊。 發生異常時,它會被緊隨其后的`catch`塊捕獲。 `catch`塊不能單獨使用,并且必須始終在`try`塊之前。 ### 示例 1:`try...catch`塊 ```java class Main { public static void main(String[] args) { try { int divideByZero = 5 / 0; System.out.println("Rest of code in try block"); } catch (ArithmeticException e) { System.out.println("ArithmeticException => " + e.getMessage()); } } } ``` **輸出** ```java ArithmeticException => / by zero ``` 在這個例子中 * 我們在`try`塊中將數字除以 0。 這產生了`ArithmeticException`。 * 發生異常時,程序將跳過`try`塊中的其余代碼。 * 在這里,我們創建了一個`catch`塊來處理`ArithmeticException`。 因此,將執行`catch`塊中的語句。 如果`try`塊中的所有語句均未生成異常,則將跳過`catch`塊。 * * * ## 多個`catch`塊 對于每個`try`塊,可以有零個或多個`catch`塊。 每個`catch`塊的參數類型指示可以處理的異常類型。 多個`catch`塊使我們能夠以不同方式處理每個異常。 ### 示例 2:多個`catch`塊 ```java class ListOfNumbers { public int[] arrayOfNumbers = new int[10]; public void writeList() { try { arrayOfNumbers[10] = 11; } catch (NumberFormatException e1) { System.out.println("NumberFormatException => " + e1.getMessage()); } catch (IndexOutOfBoundsException e2) { System.out.println("IndexOutOfBoundsException => " + e2.getMessage()); } } } class Main { public static void main(String[] args) { ListOfNumbers list = new ListOfNumbers(); list.writeList(); } } ``` **輸出**: ```java IndexOutOfBoundsException => Index 10 out of bounds for length 10 ``` 在此示例中,我們聲明了大小為 10 的整數`arrayOfNumbers`數組。 我們知道數組索引始終從 0 開始。因此,當我們嘗試為索引 10 分配值時,會出現`IndexOutOfBoundsException`,因為`arrayOfNumbers`的數組范圍是 0 到 9。 當`try`塊中發生異常時, * 異常被引發到第一個`catch`塊。 第一個`catch`塊不處理`IndexOutOfBoundsException`,因此將其傳遞到下一個`catch`塊。 * 上面示例中的第二個`catch`塊是適當的異常處理器,因為它處理`IndexOutOfBoundsException`。 因此,它被執行。 * * * ## Java `finally`塊 對于每個`try`塊,只能有一個`finally`塊。 `finally`塊是可選的。 但是,如果已定義,它將始終執行(即使不會發生異常)。 如果發生異常,則在`try...catch`塊之后執行該異常。 如果沒有異常發生,則在`try`塊之后執行。 `finally`塊的基本語法為: ```java try { //code } catch (ExceptionType1 e1) { // catch block } catch (ExceptionType1 e2) { // catch block } finally { // finally block always executes } ``` * * * ### 示例 3:`finally`塊 ```java class Main { public static void main(String[] args) { try { int divideByZero = 5 / 0; } catch (ArithmeticException e) { System.out.println("ArithmeticException => " + e.getMessage()); } finally { System.out.println("Finally block is always executed"); } } } ``` **輸出**: ```java ArithmeticException => / by zero Finally block is always executed ``` 在此示例中,我們將數字除以 0。這將引發`ArithmeticException`,該`ArithmeticException`被`catch`塊捕獲。`finally`塊始終執行。 擁有`finally`塊被認為是一個好習慣。 這是因為它包含重要的清除代碼,例如: * `return`,`continue`或`break`語句可能意外跳過的代碼 * 關閉文件或連接 我們已經提到,最后總是執行,通常就是這種情況。 但是,在某些情況下,`finally`塊不執行: * 使用`System.exit()`方法 * `finally`塊中發生異常 * 線程的死亡 * * * ### 示例 4:`try-catch-finally` 讓我們舉一個例子,我們嘗試使用`FileWriter`創建一個新文件,然后使用`PrintWriter`向其中寫入數據。 ```java import java.io.*; class ListOfNumbers { private int[] list = new int[10]; public ListOfNumbers() { // storing integer values in the list array for (int i = 0; i < 10; i++) { list[i] = i; } } } public void writeList() { PrintWriter out = null; try { System.out.println("Entering try statement"); // creating a new file OutputFile.txt out = new PrintWriter(new FileWriter("OutputFile.txt")); // writing values from list array to the new created file for (int i = 0; i < 10; i++) { out.println("Value at: " + i + " = " + list[i]); } } catch (IndexOutOfBoundsException e1) { System.out.println("IndexOutOfBoundsException => " + e1.getMessage()); } catch (IOException e2) { System.out.println("IOException => " + e2.getMessage()); } finally { // checking if PrintWriter has been opened if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else { System.out.println("PrintWriter not open"); } } } } class Main { public static void main(String[] args) { ListOfNumbers list = new ListOfNumbers(); list.writeList(); } } ``` 運行此程序時,可能會發生兩種情況: 1. `try`塊中發生異常 2. `try`塊正常執行 創建新的`FileWriter`時可能會發生異常。 如果指定的文件無法創建或寫入,則拋出`IOException`。 當發生異常時,我們將獲得以下輸出。 ```java Entering try statement IOException => OutputFile.txt PrintWriter not open ``` 當沒有異常發生并且`try`塊正常執行時,我們將獲得以下輸出。 ```java Entering try statement Closing PrintWriter ``` 創建了`OutputFile.txt`,它將具有以下內容: ```java Value at: 0 = 0 Value at: 1 = 1 Value at: 2 = 2 Value at: 3 = 3 Value at: 4 = 4 Value at: 5 = 5 Value at: 6 = 6 Value at: 7 = 7 Value at: 8 = 8 Value at: 9 = 9 ``` * * * ### `try...catch...finally`的詳細原理 讓我們嘗試在上述示例的幫助下詳細了解異常處理的流程。 ![Working of try...catch...finally in Java](https://img.kancloud.cn/e8/a5/e8a505291bdb29d5e652271b05a072eb_1200x628.png) 上圖描述了在創建新的`FileWriter`時發生異常時的程序執行流程。 * 為了進入發生異常的方法,`main`方法調用`writeList()`方法,然后調用`FileWriter()`方法來創建新的`OutputFile.txt`文件。 * 發生異常時,運行系統將跳過`try`塊中的其余代碼。 * 它開始以相反的順序搜索調用棧,以找到合適的異常處理器。 * 這里`FileWriter`沒有異常處理器,因此運行時系統檢查調用棧中的下一個方法,即`writeList`。 * `writeList`方法有兩個異常處理器:一個處理`IndexOutOfBoundsException`,另一個處理`IOException`。 * 然后,系統依次處理這些處理器。 * 此示例中的第一個處理器處理`IndexOutOfBoundsException`。 這與`try`塊引發的`IOException`不匹配。 * 因此,檢查下一個處理器是`IOException`處理器。 這與引發的異常類型匹配,因此將執行`catch`塊中的代碼。 * 執行異常處理器后,將執行`finally`塊。 * 在這種情況下,由于`FileWriter`中發生異常,因此中的`PrintWriter`對象從未被打開,因此不需要關閉。` 現在,讓我們假設在運行該程序時未發生異常,并且`try`塊正常執行。 在這種情況下,將創建并寫入一個`OutputFile.txt`。 眾所周知,無論異常處理如何,都會執行`finally`塊。 由于沒有異常發生,因此`PrintWriter`是打開的,需要關閉。 這是通過`finally`塊中的`out.close()`語句完成的。 * * * ### 捕獲多個異常 從 Java SE 7 和更高版本開始,我們現在可以使用一個`catch`塊捕獲不止一種類型的異常。 這樣可以減少代碼重復并提高代碼的簡單性和效率。 `catch`塊可以處理的每種異常類型都使用豎線`|`分隔。 其語法為: ```java try { // code } catch (ExceptionType1 | Exceptiontype2 ex) { // catch block } ``` 要了解更多信息,請訪問 [Java 捕獲多個異常](/java-programming/multiple-exceptions)。 * * * ### `try-with-resources`語句 `try-with-resources`語句是一種`try`語句,具有一個或多個資源聲明。 它的語法是: ```java try (resource declaration) { // use of the resource } catch (ExceptionType e1) { // catch block } ``` 資源是在程序結束時要關閉的對象。 必須在`try`語句中聲明和初始化它。 讓我們舉個例子。 ```java try (PrintWriter out = new PrintWriter(new FileWriter("OutputFile.txt")) { // use of the resource } ``` `try-with-resources`語句也稱為**自動資源管理**。 該語句在語句末尾自動關閉所有資源。 要了解更多信息,請訪問 [Java `try-with-resources`語句](/java-programming/try-with-resources "Java 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>

                              哎呀哎呀视频在线观看