java言語例外のカスタム定義サンプル

サンプルコード:

package com.startnews24.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;
}
}

Java

Posted by arkgame