在 Java 中,try-catch 語句可以組合使用,以便在一個 try 塊中捕獲多個異常類型。你可以使用多個 catch 塊來處理不同類型的異常,每個 catch 塊處理一種特定類型的異常。此外,你還可以在一個 catch 塊中處理多種類型的異常,只需將它們放在同一個 catch 塊中,并用管道符(|)分隔即可。
以下是一個示例,展示了如何組合使用 Java try-catch 語句:
public class TryCatchExample {
public static void main(String[] args) {
try {
// Code that might throw exceptions
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Handle ArithmeticException
System.out.println("Error: Division by zero.");
} catch (NullPointerException e) {
// Handle NullPointerException
System.out.println("Error: Null value encountered.");
} catch (Exception e) {
// Handle other types of exceptions
System.out.println("Error: An unexpected error occurred.");
} finally {
// Code that will always execute, regardless of whether an exception was thrown
System.out.println("Finally block executed.");
}
}
public static int divide(int a, int b) throws ArithmeticException {
return a / b;
}
}
在這個示例中,我們嘗試執行除法操作,該操作可能會拋出 ArithmeticException(當除數為零時)和 NullPointerException(如果傳入的參數為 null)。我們使用三個 catch 塊分別處理這些異常類型。最后,我們還使用了一個 finally 塊,它將在 try-catch 結構中的任何情況下執行。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。