《Effective Java》中的Joshua Bloch说:
对于可恢复的情况使用checked异常,对于编程错误使用runtime异常(第2版的第58项)。
让我们看看我是否正确理解了这个概念。
这是我对checked异常的理解:
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. 现在,上面的代码难道也不是一个checked异常吗?我可以像这样尝试恢复情况吗?(注意:我的第三个问题在上面的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. 我应该冒泡精确的异常信息还是使用 Exception 进行掩盖?
以下是我的阅读材料:
DataSeries
类,它保存的数据必须始终保持按时间排序。有一个方法将新的DataPoint
添加到DataSeries
的末尾。如果在整个项目中我的代码都正常工作,则不应该向末尾添加先前日期比当前末尾日期早的DataPoint
。整个项目中的每个模块都是建立在这一真理之上的。但是,如果出现此情况,我会检查该条件并抛出未被检查的异常。为什么?如果发生这种情况,我想知道是谁在这样做,并进行修复。 - Erick Robertson