Use null to encapsulate the Null class of the object.Customize an Exception class:
ProjectNameException. java content is as follows:
?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;}}
The content of ProjectNameExceptionCode. java is as follows:
?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
EXCEPTION_CODE_MAP;public static final int PROJECTNAME_EXCEPTION_CODE_NOT_FOUND = 1;static {EXCEPTION_CODE_MAP = new HashMap
();EXCEPTION_CODE_MAP.put(PROJECTNAME_EXCEPTION_CODE_NOT_FOUND,"[PROJECTNAME Exception] Not found exception code.");}}
References:
1. JDK1.7 API: http://docs.oracle.com/javase/7/docs/api/
2. Java programming ideas (version 4)
3. Valid 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
Note:
If you have any mistakes, please correct them. You are welcome to discuss them and give us some guidance.
Last Updated: