差異處
這裏顯示兩個版本的差異處。
下次修改 | 前次修改 | ||
java:effective_java:exceptions:checked_vs_unchecked [2022/04/11 23:34] tony 建立 |
java:effective_java:exceptions:checked_vs_unchecked [2023/06/25 09:48] (目前版本) |
||
---|---|---|---|
行 1: | 行 1: | ||
{{tag>java effective_java exceptions}} | {{tag>java effective_java exceptions}} | ||
- | ====== Effective Java - Use checked exceptions for recoverable conditions and runtime exceptions for programming errors (ToDo) ====== | + | ====== Effective Java - Use checked exceptions for recoverable conditions and runtime exceptions for programming errors ====== |
===== Introduction ===== | ===== Introduction ===== | ||
這個Item在強調例外的使用時機,包含 | 這個Item在強調例外的使用時機,包含 | ||
* Checked Exceptions應用在recoverable conditions | * Checked Exceptions應用在recoverable conditions | ||
* Unchecked(Runtime) Exception應用在programming errors | * Unchecked(Runtime) Exception應用在programming errors | ||
- | 下一個問題就是怎麼定義recoverable conditions與programming errors。我分享[[https://www.books.com.tw/products/0010637503|笑談軟體工程:例外處理設計的逆襲]]中的觀點,與我的看法給大家參考。 | + | 下一個問題就是怎麼定義recoverable conditions與programming errors。我分享[[https://www.books.com.tw/products/0010637503|笑談軟體工程:例外處理設計的逆襲]]中的觀點: |
- | * Programming errors: | + | * Programming errors: design fault造成的,通常代表是bug;因為是bug,所以retry 1億次也還是錯的。 |
- | * Recoverable conditions: | + | * Recoverable conditions: component fault造成的,可能是軟體元件、硬體元件突然發生故障,或與其溝通的過程中發生故障而導致的暫態缺陷,透過retry是有機會修復的。如果是永久缺陷,可能就需要排除原因才有機會執行成功。 |
+ | 根據上面的定義,就可以知道什麼時候該拋checked exception,什麼時候該拋unchecked exception了。對應到REST API的回應結果,unchecked exception預設通常都會是5xx錯誤,而checked exception就需要交給client去識別,是屬於需要user介入處理的4xx錯誤,還是server暫時的5xx錯誤。\\ | ||
+ | \\ | ||
除此之外,這個Item還有提到幾個設計要注意的事情: | 除此之外,這個Item還有提到幾個設計要注意的事情: | ||
* 按照慣例,Error應保留給JVM使用,用以表明程序無法繼續執行的情況。所以開發人員通常不該去Extend Error。 | * 按照慣例,Error應保留給JVM使用,用以表明程序無法繼續執行的情況。所以開發人員通常不該去Extend Error。 |