在學習捕獲多個異常之前,您需要熟悉Java 中的基本異常處理。接下來,我們假設您熟悉 Java 中的 try 和 catch 塊。
為什麼我們需要在 Java 中使用多個 catch 塊?
Java中的多個catch塊用於處理不同類型的異常。在 Java 7 推出之前,我們需要一個特定的 catch 塊來捕獲特定的異常。這創建了冗餘代碼塊,因此導致了一種低效的方法。看看下面的例子來見證捕獲的異常。它針對不同類型的異常使用單獨的 catch 塊。使用單獨的 Catch 塊的示例
import java.util.Arrays;
public class ExceptionHandler {
public static void main(String[] args) {
Integer[] colorsOfASpectrum = { 7, 6, 5, 4, 3, 2, 1, 0 };
try {
System.out.println("Total number of options on a dice are: " + Arrays.toString(colorsOfASpectrum));
// un-comment the following line to see "Index Out of Bounds Exception"
// colorsOfASpectrum[10] = 7; // Index Out of Bounds Exception
System.out.println(colorsOfASpectrum[0] / 0); // Arithmetic Exception
} catch (ArrayIndexOutOfBoundsException e) {
// This catch block executes in case of "Index Out of Bounds Exception"
System.out.println("Array Index Out Of Bounds Exception " + e);
} catch (ArithmeticException e) {
// This catch block executes in case of "Arithmetic Exception"
System.out.println("Arithmetic Exception " + e);
}
System.out.println("\n----Rest of the code executes here----");
}
}
輸出
光譜上的總顏色為:[7, 6, 5, 4, 3, 2, 1]
如您所見,在上面的示例中,拋出異常時會執行不同的塊。有一種更有效的方法來捕獲多個異常,使用同一代碼塊來捕獲不同類型的異常。看看下面的例子。
在 Java 中使用多個 Catch 塊的示例
import java.util.Arrays;
public class MultiExceptionHandler {
public static void main(String[] args) {
Integer[] colorsOfASpectrum = { 7, 6, 5, 4, 3, 2, 1 };
try {
System.out.println("Total colors on a spectrum are: " + Arrays.toString(colorsOfASpectrum));
// colorsOfASpectrum[10] = 7; // Index Out of Bounds Exception
System.out.println(colorsOfASpectrum[0] / 0); // Arithmetic Exception
} catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {
// We don't need two different catch blocks for different kinds of exceptions
// Both exceptions will be handled using this multiple catch block
System.out.println("Exception Encountered " + e);
}
System.out.println("\n----Rest of the code executes here----");
}
}
輸出
您可以取消註釋第 13 行以打印出其他類型的異常。
光譜上的總顏色為:[7, 6, 5, 4, 3, 2, 1]
GO TO FULL VERSION