Joshua Bloch in " Effective Java " said that 约书亚·布洛赫(Joshua Bloch)在《 有效的Java 》中说 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. 让咱们看看我是否正确理解了这一点。 ide
Here is my understanding of a checked exception: 这是我对检查异常的理解: this
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.以上是否被视为通过检查的异常? spa
2. Is RuntimeException an unchecked exception? 2. RuntimeException是未经检查的异常吗? .net
Here is my understanding of an unchecked exception: 这是我对未经检查的异常的理解: code
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
上) orm
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.人们为何这样作? get
public void someMethod throws Exception{ }
Why do they let the exception bubble up? 为何他们让异常冒出来? Isn't handling the error sooner better? 处理错误不是更好吗? Why bubble up? 为何冒泡? input
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 什么时候选择已检查和未检查的异常