這裏總結一下Java的Exception,並實現一個自定義Exception類。 html
總結: java
自定義一個Exception類: 數據庫
ProjectNameException.java 內容以下: 編程
package com.trianlge23.projectname.exception; public class ProjectNameException extends Throwable { private static final long serialVersionUID = 8093803025939797139L; //exception code private int exceptionCode; //exception detailed message private 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() @Override public String getMessage() { return this.detailMsg; } }
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 message public 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."); } }
參考資料: api
1. JDK1.7 API:http://docs.oracle.com/javase/7/docs/api/ 數組
2. Java編程思想(第四版) 安全
3. Effective Java oracle
4. Exception Handling Java Best Practices:
http://javarevisited.blogspot.com/2013/03/0-exception-handling-best-practices-in-Java-Programming.html app
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 ide
說明:
若有錯誤還請各位指正,歡迎你們一塊兒討論給出指導。
最後更新時間:2014-12-02