温馨提示×

java subtract函数异常处理

小樊
82
2024-06-24 18:23:25
栏目: 编程语言

在Java中,如果要处理subtract函数的异常,你可以使用try-catch块来捕获可能抛出的异常。下面是一个示例代码:

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函数会检查除数是否为0,如果是则会抛出ArithmeticException异常。在main函数中,我们使用try-catch块捕获这个异常,然后打印出错误消息。这样可以保证程序不会崩溃,而是能够优雅地处理异常情况。

0