Java自訂Exception,javaexception
這裡總結一下Java的Exception,並實現一個自訂Exception類。
總結:
- Throwable對象分為兩種類型:Error(表示編譯時間和系統錯誤);Exception(在Java類庫、使用者方法以及運行時故障中拋出的異常)。
- Exception細分成兩種異常:受檢查異常(如,IOException, SQLException等。在編譯時間要被強制檢查的異常,需要用try, catch, finally關鍵字在編譯時間期處理,否則會報錯。);運行時異常(如,ArithmeticException, ClassCastException, IllegalArgumentException, IndexOutOfBoundsException, NullPointerException等。編譯器不會檢查這類異常。)
- Java編程中處理異常的最佳實務[4]:
- 為可恢複的錯誤使用檢查型異常,為編程錯誤使用非檢查型錯誤。
- 在finally程式塊中關閉或者釋放資源
- 在堆疊追蹤中包含引起異常的原因
- 始終提供關於異常的有意義的完整的信
- 避免過度使用檢查型異常
- 將檢查型異常轉為運行時異常
- 記住對效能而言,異常代價高昂
- 避免catch塊為空白
- 使用標準異常
- 記錄任何方法拋出的異常
- 受檢查異常和運行時異常的區別:
- 受檢查異常需要自行處理,運行時異常不需要
- 受檢查異常是Exception直接子類,運行時異常是RuntimeException的子類
- 受檢查異常多是編程時出現的錯誤,運行時異常是程式運行時故障率較高
- 避免出現NullPointerException的最佳實務[5]:
- 用已知的字串對象調用equals()和equalsIgnoreCase()方法【"hello".equals(objString)】;
- 如果valueOf()和toString()方法的返回值一樣的話,用valueOf()方法代替toString()方法【當為null的對象調用toString()方法時會拋出NullPointerException異常而調用valueOf()方法時會返回一個"null"的封裝類】;
- 使用對null安全的方法和庫【eg, StringUtils.isBlank(), isNumeric(), isWhiteSpace()等】;
- 方法調用的返回值用返回空的集合或者空的數組避免返回null的情況【Collections.EMPTY_LIST, Collections.EMPTY_SET和Collections.EMPTY_MAP等】;
- 使用@NotNull和@Nullable的註解明確指出是否可能有null的情況出現;
- 避免代碼中出現不必要的自動裝箱和拆箱【避免類似的int a 出現接收返回值為null的情況,用Integer a代替更好】;
- 遵守契約並且使用合理的預設值【通過定義什麼可以為空白,什麼不可為空,主叫方可以明確的作出判斷。】;
- 在使用資料庫儲存物件時,要定義是否允許某個欄位為空白,這樣資料庫自身機制可以檢查是否為空白的情況,避免程式調用後出現非法的空欄位。
- 使用null的封裝對象Null類。
自訂一個Exception類:
ProjectNameException.java 內容如下:
?
package com.trianlge23.projectname.exception;public class ProjectNameException extends Throwable {private static final long serialVersionUID = 8093803025939797139L;//exception codeprivate int exceptionCode;//exception detailed messageprivate String detailMsg;public ProjectNameException(int exceptionCode, String extraMsg) {super();this.setDetailMsg(exceptionCode);this.setExtraMsg(extraMsg);}public ProjectNameException(int exceptionCode) {super();this.setDetailMsg(exceptionCode);}//notice: we do not offer the set method to set the excption code.public int getExceptionCode() {return exceptionCode;}//if there has no extra message for this excption code, init it.private void setDetailMsg(int exceptionCode) {this.exceptionCode = exceptionCode;if (ProjectNameExceptionCode.EXCEPTION_CODE_MAP.containsKey(exceptionCode)) {this.detailMsg = ProjectNameExceptionCode.EXCEPTION_CODE_MAP.get(exceptionCode);} else {this.detailMsg = ProjectNameExceptionCode.EXCEPTION_CODE_MAP.get(ProjectNameExceptionCode.PROJECTNAME_EXCEPTION_CODE_NOT_FOUND);}}//if there has extra message for this exception code, add it.private void setExtraMsg(String extraMsg) {this.detailMsg += ProjectNameExceptionCode.EXTRA_EXCEPTION_MSG_SPLITER+ extraMsg;}//override the super class method getMessage()@Overridepublic String getMessage() {return this.detailMsg;}}
ProjectNameExceptionCode.java內容如下:
?
package com.triangle23.projectname.exception;import java.util.HashMap;import java.util.Map;public class ProjectNameExceptionCode {//the separator between default message and extra message of exception.public static final String EXTRA_EXCEPTION_MSG_SPLITER = ": ";//the map stores the exception code and exception messagepublic static Map<Integer, String> EXCEPTION_CODE_MAP;public static final int PROJECTNAME_EXCEPTION_CODE_NOT_FOUND = 1;static {EXCEPTION_CODE_MAP = new HashMap<Integer, String>();EXCEPTION_CODE_MAP.put(PROJECTNAME_EXCEPTION_CODE_NOT_FOUND,"[PROJECTNAME Exception] Not found exception code.");}}
參考資料:
1. JDK1.7 API:http://docs.oracle.com/javase/7/docs/api/
2. Java編程思想(第四版)
3. Effective Java
4. Exception Handling Java Best Practices:
http://javarevisited.blogspot.com/2013/03/0-exception-handling-best-practices-in-Java-Programming.html
5. Java Tips and Best practices to avoid NullPointerException:
http://javarevisited.blogspot.com/2013/05/java-tips-and-best-practices-to-avoid-nullpointerexception-program-application.html
說明:
如有錯誤還請各位指正,歡迎大家一起討論給出指導。
最後更新時間:2014-12-02