当第三方使用你封装的程序工作时,一些判断是否符合逻辑的错误,想以异常的方式提醒第三方,需要自定义异常类
自定义异常类需要 继承 Exception
public class DemoException extends Exception {
/**
*
*/
/*
* 错误详情
*/
private String exMsg;
/*
* 错误码
*/
private String exCode;
public String getExMsg() {
return exMsg;
}
public void setExMsg(String exMsg) {
this.exMsg = exMsg;
}
public String getExCode() {
return exCode;
}
public void setExCode(String exCode) {
this.exCode = exCode;
}
/**
*
* @param msg 异常信息
* @param exMsg 扩展信息
*/
public DemoException(String exMsg,String exCode) {
super(exMsg);
this.setExMsg(exMsg);
this.setExCode(exCode);
}
}
使用自定义异常
import org.springframework.stereotype.Service;
import study.com.exception.DemoException;
@Service
public class JdPay {
public Boolean PayMoney(int m) throws DemoException{
if (m<=0){
throw new DemoException("金额必须大于0","001");
}
return false;
}
}
调用方
public String Index(){
try {
jdPay.PayMoney(0);
} catch (DemoException e) {
System.out.println("错误信息:"+e.getExMsg()+";错误码:"+e.getExCode());
}
return "2556546546";
}