Checked exceptions 应该用于可以合理地恢复调用者的条件。通过抛出已检查的异常,您将强制调用者在 catch clause 中处理异常或将其向外传播。 API 用户可以通过捕获Exception 并采取适当的恢复步骤从异常情况中恢复。
例如,FileNotFoundException 是 checked exception:
try {
FileInputStream fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
// HANDLE THE EXCEPTION
}
即使找不到文件,如果用户有适当的恢复步骤(从不同位置读取文件等),应用程序也可以继续执行。
另一方面,Runtime exceptions 应该用于表示无法恢复并且继续执行会造成更大的伤害。很多时候,runtime exceptions 用于指示违反前提条件:已定义为使用您的 API 的合约被您的 API 的客户端违反。
例如,ArrayIndexOutOfBoundsException 是 runtime exception:
int[] aa = new int[2];
int ii = aa[2]; // java.lang.ArrayIndexOutOfBoundsException
因为访问数组元素的约定规定数组索引必须在零和数组长度减一之间,而我们违反了上面的前提条件。
再次,假设您正在编写一个类Address,如下所示,其中areaCode 不能是null。如果有人在没有areaCode 的情况下创建了Address,那么将来使用Address 时可能会造成更大的伤害。在这里,您可以使用IllegalArgumentException(这是一个运行时异常)来表示:
public class Address {
private String areaCode;
public Address(String areaCode) {
if (areaCode == null) {
throw new IllegalArgumentException("Area Code cannot be NULL");
}
this.areaCode = areaCode;
}
...
}
因此,建议在可以恢复的地方使用checked exceptions,如果无法恢复或违反任何先决条件,最好使用Runtime exception。