首页 > 解决方案 > “抛出 ArithmeticException”是否只是方法定义中的装饰?

问题描述

我决定throws ArithmeticException在下面的代码中删除,当我除以零并出现堆栈跟踪时,我仍然得到相同的结果。在方法定义中是throws ArithmeticException可选的吗?它的目的是什么?

public static int quotient(int numerator, int denominator) throws ArithmeticException {
    return numerator / denominator;
}

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    try {
        int denominator = scanner.nextInt();
        System.out.println(quotient(10, denominator));
    } catch(ArithmeticException e) {
        System.out.println("Aritmetic exception");
    } catch(InputMismatchException e) {
        System.out.println("InputMismatchException");
    }
}

标签: java

解决方案


ArithmeticException是 的子类RuntimeException,与大多数异常不同,RuntimeExceptions 是未经检查的,因此不需要在声明中throws声明。所以是的,这是不必要的。


推荐阅读