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 什麼時候選擇已檢查和未檢查的異常