gpt4 book ai didi

java - 为什么我不能在方法中抛出异常(Java)

转载 作者:搜寻专家 更新时间:2023-10-31 08:19:57 24 4
gpt4 key购买 nike

我是 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 block 捕获。但是 Exception 不是 RuntimeException

Section 11.2 of the JLS包括这个:

The unchecked exception classes (§11.1.1) are exempted from compile-time checking.

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

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

关于java - 为什么我不能在方法中抛出异常(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20156973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com