“抛出ArithmeticException”是否仅是方法定义中的修饰?

Zol*_*ing 5 java

我决定删除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");
    }
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*ica 8

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