在Java中,抛出 checked 异常(Exception或其子类型 - IOException,InterruptedException等)的方法必须声明 throws 语句:
public abstract int read() throws IOException;
不声明 throws 语句 can't 抛出已检查异常的方法 .
public int read() { // does not compile
throw new IOException();
}
// Error: unreported exception java.io.IOException; must be caught or declared to be thrown
但是在安全方法中捕获已检查的异常在java中仍然是合法的:
public void safeMethod() { System.out.println("I'm safe"); }
public void test() { // method guarantees not to throw checked exceptions
try {
safeMethod();
} catch (Exception e) { // catching checked exception java.lang.Exception
throw e; // so I can throw... a checked Exception?
}
}
实际上,没有 . 这有点好笑:编译器知道 e 不是一个经过检查的异常并允许重新抛出它 . 事情甚至有点荒谬,这段代码不编译:
public void test() { // guarantees not to throw checked exceptions
try {
safeMethod();
} catch (Exception e) {
throw (Exception) e; // seriously?
}
}
// Error: unreported exception java.lang.Exception; must be caught or declared to be thrown
第一个片段是一个问题的动机 .
编译器知道检查的异常不能被抛出一个安全的方法 - 所以也许它应该只允许捕获未经检查的异常?
回到 main question - 有没有理由以这种方式实现捕获检查的异常?这只是设计中的缺陷还是我遗漏了一些重要因素 - 可能是后向不兼容?如果在这种情况下只允许 RuntimeException 被捕获,可能会出现什么问题?非常感谢例子 .