2016年4月6日 星期三

Java Exception

http://villebez.logdown.com/posts/2016/04/01/java-exception
java exception hierarchy
Exception Hierarchy DiagramException Hierarchy Diagram
圖片來源:http://java5tutor.info/java/flowcontrol/exceptionover.html

checked exceptions and unchecked exceptions

Use checked exceptions for recoverable conditions and runtime (unchecked) exceptions for programming errors.

checked Exception

程式如果違反handle-or-declare rule,將被Java Compiler視為『語法錯誤』,程式無法編譯成功。
handle-or-declare rule
  • Handle the exception by using the try-catch-finally block.
  • Declare that the code causes an exception by using the throws clause.

unchecked Exception

不需要補抓的錯誤,例如:RuntimeException、NullPointerException...等等

JAVA異常處理中的原則和建議

原則:不要忽略checked Exception

忽略可能導致兩個結果:
由於這裡的異常導致在程序中別的地方拋出一個異常,這種情況會使工程師在除錯時感到迷惑,因為新的異常拋出的地方並不是程式真正發生問題的地方,也不是發生問題的真正原因。
程序繼續運行,並得出一個錯誤的輸出結果,這種問題更加難以捕捉,因為很可能把它當成一個正確的輸出。

建議:不要捕獲unchecked Exception

Error
RuntimeException
ex:NullPointException, IndexOutofBoundsException
例外情況:Daemon Thread (長時間運行的背景程式)

原則:不要直接 catch 最上層的 Exception

不同Exception需要不同的處裡與恢復機制
可能拋出RuntimeException

原則:使用finally釋放資源

檔案串流,DB、Socket、FTP Connection

原則:finally不能拋出異常

會導致真正的異常訊息遺失

原則:拋出自定義異常時帶上原始異常訊息

new MyException(key+“:”+e.getMessage);
new MyException(key, e);

原則:print Exception Stack, not just message

原則:

If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

怎麼做??

沒有留言:

張貼留言