当您使用知道该做什么的方法时,应该捕获异常。
例如,忘记当前的实际工作原理,假设您正在编写一个用于打开和读取文件的库。
所以你有一个班,说:
public class FileInputStream extends InputStream {
public FileInputStream(String filename) { }
}
现在,让我们说文件不存在。你该怎么办?如果您正在努力想到答案,那是因为没有一个… FileInputStream不知道该怎么做。所以它把它链起来,即:
public class FileInputStream extends InputStream {
public FileInputStream(String filename) throws FileNotFoundException { }
}
现在,让我们说一个人使用你的图书馆。他们可能会有如下代码:
public class Main {
public static void main(String... args) {
String filename = "foo.txt";
try {
FileInputStream fs = new FileInputStream(filename);
// The rest of the code
} catch (FileNotFoundException e) {
System.err.println("Unable to find input file: " + filename);
System.err.println("Terminating...");
System.exit(3);
}
}
}
在这里,程序员知道该怎么做,所以他们捕获异常并处理它。