自定义异常类
public class ServiceRuntimeException extends RuntimeException{
private String code;
public ServiceRuntimeException(String code) {
this.code=code;
}
public ServiceRuntimeException(String code,String message) {
super(message);
this.code=code;
}
@Override
public String toString() {
return "ServiceRuntimeException{" +
"code='" + code + '\'' +
'}';
}
public String getCode() {
return this.code;
}
}
/**
*
* 其他异常
*/
public class OtherRumtimeException extends RuntimeException {
public OtherRumtimeException(String message) {
super(message);
}
}
抛出异常:
throw new ServiceRumtimeException("000","测试");
然后在try catch中就能捕获这个异常了
try {
} catch (Exception e) {
//e.getMessage() 的值就是:测试
//
}
如何要获取code的值,应该捕获ServiceRuntimeException
自定义异常,这样才能e.getCode()
,不然没有这个方法,毕竟父类Exception
可没有我们定义的code