【发布时间】:2011-09-01 05:37:57
【问题描述】:
Joshua Bloch 在“Effective Java”中说过
使用检查的异常 可恢复的条件和运行时间 编程错误的例外 (第 2 版第 58 条)
让我们看看我是否理解正确。
这是我对已检查异常的理解:
try{
String userInput = //read in user input
Long id = Long.parseLong(userInput);
}catch(NumberFormatException e){
id = 0; //recover the situation by setting the id to 0
}
1.以上是否被视为已检查异常?
2。 RuntimeException 是未经检查的异常吗?
这是我对未经检查的异常的理解:
try{
File file = new File("my/file/path");
FileInputStream fis = new FileInputStream(file);
}catch(FileNotFoundException e){
//3. What should I do here?
//Should I "throw new FileNotFoundException("File not found");"?
//Should I log?
//Or should I System.exit(0);?
}
4.现在,上面的代码不能也是一个检查异常吗?我可以尝试恢复这种情况吗?我可以吗?(注意:我的第三个问题在上面的catch 内)
try{
String filePath = //read in from user input file path
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
}catch(FileNotFoundException e){
//Kindly prompt the user an error message
//Somehow ask the user to re-enter the file path.
}
5.人们为什么要这样做?
public void someMethod throws Exception{
}
为什么他们让异常冒泡?越早处理错误不是更好吗?为什么要冒泡?
6.我应该冒泡确切的异常还是使用异常来掩盖它?
以下是我的读数
In Java, when should I create a checked exception, and when should it be a runtime exception?
【问题讨论】:
-
我有一个很好的未检查异常示例。我有一个
DataSeries类,它保存必须始终按时间顺序排列的数据。有一种方法可以将新的DataPoint添加到DataSeries的末尾。如果我的所有代码在整个项目中都可以正常工作,那么永远不要将DataPoint添加到末尾,因为它的日期早于已经在末尾的那个。整个项目中的每个模块都是按照这个道理构建的。但是,我检查此条件并在发生时抛出未经检查的异常。为什么?如果发生这种情况,我想知道是谁在做这件事并修复它。 -
增加更多混乱。大约 10 年前,很多人都在提倡检查异常,但如今的观点越来越倾向于“检查异常是不好的”。 (但我不同意)
-
只有当你有一些有用的事情来处理异常时它才有用,否则你应该让调用者处理它。记录它并假装它没有发生通常是没有用的。只是重新扔它是没有意义的。包装 RuntimeException 并不像某些人想象的那么有用,它只会让编译器停止帮助你。 (恕我直言)
-
我们应该停止使用具有全面误导性的 checked/unchecked 异常术语。它们应该被称为 check-mandated vs check-not-mandated 例外。
-
我也想过第 5 点 public void method_name throws Exception{} 为什么有些人会这样做?
标签: java exception runtimeexception checked-exceptions unchecked-exception