我是Java的新手,并且在抛出异常时遇到了一些问题。即,为什么这是不正确的

public static void divide(double x, double y){
    if(y == 0){
    throw new Exception("Cannot divide by zero.");
        //Generates error message that states the exception type is unhanded
}
else
    System.out.println(x + " divided by " + y + " is " + x/y);
    //other code follows
}

但这好吗?
public static void divide(double x, double y){
if(y == 0)
    throw new ArithmeticException("Cannot divide by zero.");
else
    System.out.println(x + " divided by " + y + " is " + x/y);
    //other code follows
}

最佳答案

ArithmeticException RuntimeException,因此不需要在throws子句中声明或被catch块捕获。但是Exception不是RuntimeException

Section 11.2 of the JLS涵盖了这一点:



“未经检查的异常类”包括ErrorRuntimeException

此外,您将要检查y是否为0,而不是x / y是否为0

10-08 05:12