了解Java中的检查与未检查异常

不羁的心 提交于 2020-05-03 15:55:43

问题:

Joshua Bloch in " Effective Java " said that 约书亚·布洛赫(Joshua Bloch)在《 有效的Java 》中说

Use checked exceptions for recoverable conditions and runtime exceptions for programming errors (Item 58 in 2nd edition) 将检查的异常用于可恢复的条件,将运行时异常用于编程错误(第二版中的项目58)

Let's see if I understand this correctly. 让我们看看我是否正确理解了这一点。

Here is my understanding of a checked exception: 这是我对检查异常的理解:

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. Is the above considered a checked exception? 1.以上是否被视为经过检查的异常?

2. Is RuntimeException an unchecked exception? 2. RuntimeException是未经检查的异常吗?

Here is my understanding of an unchecked exception: 这是我对未经检查的异常的理解:

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. Now, couldn't the above code also be a checked exception? 4.现在,上面的代码难道不是一个检查异常吗? I can try to recover the situation like this? 我可以尝试恢复这种情况吗? Can I? 我可以吗? (Note: my 3rd question is inside the catch above) (注:我的第三个问题是,里面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. Why do people do this? 5.人们为什么这样做?

public void someMethod throws Exception{

}

Why do they let the exception bubble up? 为什么他们让异常冒出来? Isn't handling the error sooner better? 处理错误不是更好吗? Why bubble up? 为什么冒泡?

6. Should I bubble up the exact exception or mask it using Exception? 6.我应该冒充确切的异常还是使用Exception屏蔽它?

Below are my readings 以下是我的读物

In Java, when should I create a checked exception, and when should it be a runtime exception? 在Java中,什么时候应该创建一个检查异常,什么时候应该是运行时异常?

When to choose checked and unchecked exceptions 何时选择已检查和未检查的异常


解决方案:

参考一: https://stackoom.com/question/Pf1U/了解Java中的检查与未检查异常
参考二: https://oldbug.net/q/Pf1U/Understanding-checked-vs-unchecked-exceptions-in-Java
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!