Java 如何自定义一个异常类

Java  如何自定义一个异常类

问题描述:

Java 如何自定义一个异常类
/**
*需要以书面语言的形式详细说出,考试题目急!!!!
*/

自定义一个业务处理异常类

  1. 新建一个一个业务处理异常类BusinessException.class, 继承运行时异常类RuntimeException.class;
  2. 在BusinessException类中定义两个属性错误码errorCode和错误信息,message;
  3. 编写构造参数,两个有参,一个无参构造函数,构造函数中继承父类
    代码如下:
public class BusinessException extends RuntimeException {
    private Integer errorCode;
    private String message;

   public BusinessException() {
        super();
    }
    public BusinessException(String message) {
        super(message);
        this.message = message;
    }

    public BusinessException(Integer errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
        this.message = message;
    }
}

自定义异常类(需要继承异常父类)


public class MyException extends Exception {
    
    private static final long serialVersionUID = 1L;
    private Integer code;
    private String msg;

    public MyException(String msg, Integer code){
        super(msg);
        this.code = code;
        this.msg  = msg;
    }
    public void setCode(Integer code) {
        this.code = code;
    }

    public Integer getCode() {
        return code;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getMsg() {
        return msg;
    } 
}

抛出自定义异常

public class exceptionMethod throws MyException {
    //抛出异常不可执行return
    public Integer methodTest(String text) throws MyException {

        if (text == null) {
            MyException exception = new MyException(ErrInfo.ERROR_MESSAGE, ErrInfo.ERROR_CODE);
            throw exception;
        }
        return text;
    }
}