我用 Java 编码已经有一段时间了。但有时,我不明白什么时候应该抛出异常,什么时候应该捕获异常。我正在做一个有很多方法的项目。层次结构是这样的-
Method A will call Method B and Method B will call some Method C and Method C will call Method D and Method E.
所以目前我正在做的是 - 我在所有方法中抛出异常并在方法 A 中捕获它,然后记录为错误。
但我不确定这是否是正确的做法?或者我应该开始在所有方法中捕获异常。所以这就是为什么这种困惑始于我的——我什么时候应该捕获异常与什么时候应该抛出异常。我知道这是一个愚蠢的问题,但不知何故我很难理解这个主要概念。
谁能给我一个详细的例子,说明何时捕获异常与何时抛出异常
,以便我的概念得到澄清?就我而言,我应该继续抛出异常,然后在主调用方法 A 中捕获它吗?
最佳答案
当您在知道该做什么的方法中时,您应该捕获异常。
例如,暂时忘记它的实际工作原理,假设您正在编写一个用于打开和读取文件的库。
所以你有一个类,说:
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 - 何时捕获异常与何时抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18679090/