标签:blog http io ar color os 使用 sp java
原文地址:http://my.oschina.net/liuzeli/blog/351280
这里总结一下Java的Exception,并实现一个自定义Exception类。
总结:
自定义一个Exception类:
ProjectNameException.java 内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
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; } } |
ProjectNameExceptionCode.java内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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." ); } } |
参考资料:
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
标签:blog http io ar color os 使用 sp java
原文地址:http://www.cnblogs.com/AloneSword/p/4142049.html