【发布时间】:2013-02-21 05:21:39
【问题描述】:
一般来说,Java 中有两种处理异常的方法。
- 在方法签名中添加 throws 声明
- 用 try/catch 块包围。
但是,我注意到一些异常,尤其是从RuntimeException 继承的异常,不需要这种显式的异常处理。
例如,我创建了如下示例方法,并为不需要显式异常处理的方法标记了“不需要”。
public void textException(){
int i = (new Random()).nextInt(100);
switch (i){
case 1:
throw new NullPointerException(); //Not required
case 2:
throw new NumberFormatException(); //Not required
case 3:
throw new RuntimeException(); //Not required
case 4:
throw new ClassNotFoundException(); //Required
case 5:
throw new IOException(); //Required
case 6:
throw new Exception(); //Required
default:
return;
}
}
我注意到RuntimeException 继承自Exception。
为什么RuntimeException 不需要被显式捕获来编译而其他Exceptions 需要?
【问题讨论】:
-
这些在 Java 中被称为 Checked 和 Unchecked 异常。这些已经在 SO 中讨论过很多次了,请查看 stackoverflow.com/questions/6115896/…
-
方法不需要在其 throws 子句中声明任何可能在方法执行期间抛出但未被捕获的 RuntimeException 子类。