溫馨提示×

如何在trycatch中處理多個異常

小樊
144
2024-09-03 04:01:47
欄目: 編程語言

在Java中,您可以使用try-catch語句處理多個異常

public class MultipleExceptionHandling {
    public static void main(String[] args) {
        try {
            int result1 = riskyOperation1();
            int result2 = riskyOperation2();
            int result3 = riskyOperation3();
        } catch (ArithmeticException e) {
            System.out.println("ArithmeticException: " + e.getMessage());
        } catch (NullPointerException e) {
            System.out.println("NullPointerException: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("Other exception: " + e.getMessage());
        }
    }

    private static int riskyOperation1() {
        // Your code here
    }

    private static int riskyOperation2() {
        // Your code here
    }

    private static int riskyOperation3() {
        // Your code here
    }
}

在這個示例中,我們在一個try塊中調用了三個方法,每個方法都有可能拋出不同類型的異常。然后,我們使用了多個catch塊來處理可能發生的異常。

注意,catch塊的順序很重要。當異常被拋出時,Java運行時系統會從上到下檢查catch塊,找到第一個與異常類型匹配的catch塊。因此,將最具體的異常類放在前面,最不具體的異常類(如Exception)放在最后。如果不按照這個順序,可能會導致捕獲不到預期的異常。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女