Java:已检查vs未经检查的异常说明
我已经在StackOverFlow上阅读了有关已检查和未经检查的异常的多个帖子。老实说,我还是不太确定如何正确使用它们。
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.现在,上述代码也不能成为检查异常吗?我可以尝试恢复这样的情况吗?我可以吗?(注意:我的第3个问题在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{}他们为什么要让异常泡沫化?是不是更快地处理错误?为什么泡起来?
编辑:我应该冒泡确切的异常或使用异常掩盖它吗?
以下是我的阅读材料
在Java中,何时应该创建一个已检查的异常,何时应该是运行时异常?
收到一只叮咚
慕姐4208626
相关分类