有人可以解释一下什么时候使用关键字 throw new .. 而不是在方法签名旁边使用 throws 有用吗?
我知道当一个方法抛出一个检查异常时。Java 强制我们通过直接在方法中处理异常来处理它,将异常处理到 try-catch 块中,或者通过签名旁边的关键字 throws 指定它将在其他地方完成。
但是,我很难理解何时使用关键字 throw new 有用以及为什么有用。它与处理未经检查的异常有关吗?
例如在这个例子中。为什么我们不在compute方法中抛出new ArithmeticException()呢?既然 ArithmeticException 是一种未经检查的异常?我们不应该添加类似的东西吗?
private static int compute(int i) {
if(i == 0) {
throw new ArithmeticException();
}
return 1/i;
}
Run Code Online (Sandbox Code Playgroud)
。
public class Main {
public static void main(String[] args) {
for (int i = -2; i < 2; i++) {
try {
System.out.println(i+" -> "+compute(i));
} catch (ArithmeticException e) {
System.out.println(i+" -> undefined")
}
}
}
private static int compute(int i) {
return 1/i;
}
Run Code Online (Sandbox Code Playgroud)
}
throws告诉其他人这个方法可以抛出异常。将其视为文档。检查异常必须是方法签名的一部分。
throw实际上抛出了异常。(throw new Exception();首先创建一个新的异常实例,然后抛出该实例。您可以使用两个单独的语句:)Exception ex = new Exception(); throw ex;您可以使用关键字抛出已检查和未检查的异常throw。
void checked() throws Exception { // required, Exception is a checked exception
throw new Exception();
}
void unchecked() {
throw new RuntimeException(); // throws not required, RuntimeException is not checked
}
void checkedCall() throws Exception {
checked(); // throws required, because "checked" can throw a checked exception
}
void caught() {
try {
checked();
} catch (final Exception ex) {
// throws is no longer required, because the (checked) exception is handled within the method itself. It never leaves the method.
}
}
Run Code Online (Sandbox Code Playgroud)
关于您更新的问题:您不需要throw new ArithmeticException,因为它是由 JVM 在尝试应用/运算符时抛出的。如果您愿意,您可以手动抛出它,但这只是多余的代码。
| 归档时间: |
|
| 查看次数: |
437 次 |
| 最近记录: |