java subtract函數(shù)異常處理

小樊
84
2024-06-24 18:23:25

在Java中,如果要處理subtract函數(shù)的異常,你可以使用try-catch塊來(lái)捕獲可能拋出的異常。下面是一個(gè)示例代碼:

public class Main {
    public static void main(String[] args) {
        try {
            int result = subtract(5, 3);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("An error occurred: " + e.getMessage());
        }
    }

    public static int subtract(int a, int b) {
        if (b == 0) {
            throw new ArithmeticException("Cannot divide by zero");
        }
        return a - b;
    }
}

在上面的示例中,subtract函數(shù)會(huì)檢查除數(shù)是否為0,如果是則會(huì)拋出ArithmeticException異常。在main函數(shù)中,我們使用try-catch塊捕獲這個(gè)異常,然后打印出錯(cuò)誤消息。這樣可以保證程序不會(huì)崩潰,而是能夠優(yōu)雅地處理異常情況。

0