public class ExceptionExample {
    public static void main(String[] args) {
        try {
            // 尝试执行可能抛出异常的代码
            int result = divide(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            // 捕获并处理 ArithmeticException 异常
            System.out.println("An arithmetic exception occurred: " + e.getMessage());
        } catch (Exception e) {
            // 捕获并处理其他类型的异常
            System.out.println("A general exception occurred: " + e.getMessage());
        }
    }
    public static int divide(int a, int b) {
        // 可能会抛出 ArithmeticException 的方法
        return a / b;
    }
}divide(10, 0) 会导致 ArithmeticException,因为除以零是非法操作。ArithmeticException,然后捕获所有其他类型的异常(通过 Exception)。catch 块,并打印出异常信息。上一篇:java xml解析
下一篇:java取绝对值
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站