这里总结一下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