我是 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
}
An ArithmeticException is a RuntimeException
,所以不需要在 a 中声明throws
条款或被抓住catch
堵塞。但Exception
不是一个RuntimeException
.
JLS 第 11.2 节涵盖这个:
未经检查的异常类(第 11.1.1 节)免于编译时检查。
“未经检查的异常类”包括Error
s and RuntimeException
s.
此外,您还需要检查是否y
is 0
,不是如果x / y
is 0
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)