在实际的工作中,通常需要定义自己功能模块相关的异常,下面一个实例可以实现定义自己的异常:
1.定义一个异常码抽象类作为基类
public abstract class BaseExceptionCode {
private String errorMessage ;
private int errorCode ;
private final BaseExceptionCode display ;
public BaseExceptionCode(String errorMessage,int errorCode){
this.errorMessage = errorMessage;
this.errorCode = errorCode ;
this.display = this ;
}
public BaseExceptionCode(int errorCode,String errorMessage){
this.errorCode = errorCode ;
this.errorMessage = errorMessage ;
this.display = this ;
}
public String getErrorMessage(){
return errorMessage ;
}
public int getErrorCode(){
return errorCode ;
}
public BaseExceptionCode getDisplay(){
return display ;
}
}
public class MyExceptionCode extends BaseExceptionCode{
protected MyExceptionCode(String errorMessage,int errorCode){
super(errorMessage,errorCode);
}
protected MyExceptionCode(int errorCode,String errorMessage){
super(errorCode,errorMessage);
}
public static final MyExceptionCode E_PARAM_IS_NULL_A = new MyExceptionCode(ConstantWithExceptionMsg.E_PARAM_NULL,ConstantWithExceptionCode.E_PARAM_CODE);
public static final MyExceptionCode E_PARAM_IS_NULL_B = new MyExceptionCode(ConstantWithExceptionCode.E_PARAM_CODE,ConstantWithExceptionMsg.E_PARAM_NULL);
}
3.定义自己的异常码集合(常量)
/**
* 异常码集合
*/
public class ConstantWithExceptionCode {
public static final int E_PARAM_CODE = 100001 ;
}
/**
* 异常信息
*/
public class ConstantWithExceptionMsg {
public static final String E_PARAM_NULL = "参数为空" ;
}
5.定义自己的异常
public class MyException extends RuntimeException{
private static final long serialVersionUID = -1933116620478022916L;
private String errorMessage ; //异常信息
private MyExceptionCode errorCode ; //异常码
public MyException(MyExceptionCode errorCode){
super(errorCode.getErrorMessage());
this.errorCode = errorCode ;
this.errorMessage = errorCode.getErrorMessage();
}
public MyException(String errorMessage,MyExceptionCode errorCode){
super(errorMessage);
this.errorMessage = errorMessage ;
this.errorCode = errorCode ;
}
public MyException(MyExceptionCode errorCode,String errorMessage){
super(errorMessage);
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
public String getErrorMessage(){
return errorMessage ;
}
public MyExceptionCode getErrorCode(){
return errorCode ;
}
}
6.测试自己的异常
public class MyExceptionTest {
public static void main(String[] args){
try{
test("","");
}catch(MyException e){
System.out.println(e);
throw e ;
}
}
private static void test(String str1,String str2) throws MyException{
if("".equals(str1) || str1 == null || "".equals(str2) || str2 == null ){
throw new MyException(MyExceptionCode.E_PARAM_IS_NULL_A);
}else{
return ;
}
}
}
7.测试结果
com.zh.exception.MyException: 参数为空
Exception in thread "main" com.zh.exception.MyException: 参数为空
at com.zh.exception.MyExceptionTest.test(MyExceptionTest.java:16)
at com.zh.exception.MyExceptionTest.main(MyExceptionTest.java:6)