- 为什么要使用自定义异常
- 当前JDK内置的异常不满足需求、项目会出现特有的业务场景异常
- 自定义异常可以让业务更清晰
- 如何进行自定义异常
- 异常都是继承自Exception类、所以我们自定义的异常也需要继承这个基类
- 例子
public class BaseException extends Exception { private String errorMessage; private String errorCode; public BaseException(String errorCode,String errorMessage){ super(errorMessage); this.errorCode = errorCode; this.errorMessage = errorMessage; } public String getErrorMessage() { return errorMessage; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } }
/** * @ClassName: UserNotEnoughException * @Author: mr.chen * @Date:2021/2/17 * @Email : 794281961@qq.com * @Version: 1.0 **/ public class UserNotEnoughException extends Exception { private int code; private String msg; public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } // 无参构造函数 public UserNotEnoughException() { super(); } // 有参构造函数 public UserNotEnoughException(int code, String msg) { // super 一定要放在第一行 super(msg); this.code = code; this.msg = msg; } }
/** * @ClassName: CustomException * @Author: mr.chen * @Date:2021/2/17 * @Email : 794281961@qq.com * @Version: 1.0 **/ public class CustomException { public static void main(String[] args) { try { test(); } catch (UserNotEnoughException e) { int code = e.getCode(); String msg = e.getMsg(); e.printStackTrace(); System.out.println("code= " + code + ",msg=" + msg); } catch (NullPointerException e) { e.printStackTrace(); } } public static void test() throws UserNotEnoughException { throw new UserNotEnoughException(-1, "人员不够异常"); } }