当您使用知道该做什么的方法时,应该捕获异常。
例如,忘记当前的实际工作原理,假设您正在编写一个用于打开和读取文件的库。
所以你有一个班,说:
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);
}
}
}
在这里,程序员知道该怎么做,所以他们捕获异常并处理它。
当在Java中使用FileInputStream尝试打开不存在的文件时,会抛出FileNotFoundException。这个异常表明文件未找到。通过在构造函数中声明该异常,可以让调用者通过try-catch块捕获并处理这种情况。在示例代码中,程序员捕获了异常,打印错误信息并终止程序,展示了正确的异常处理方式。
12万+

被折叠的 条评论
为什么被折叠?



