Java基础之自定义异常

307 阅读1分钟

为什么要使用自定义异常

  • 当前JDK内置的异常不满⾜需求,项⽬会出现特有异常
  • ⾃定义异常可以让业务更清晰

自定义异常的操作

  • 异常都是继承⾃Exception类,所以我们要⾃定义的异常也需要继承这个基类。

例子:

package cn.study;

public class UserNotEnoughException extends Exception{
    private int code;
    private String msg;

    public UserNotEnoughException() {
        super();
    }

    public UserNotEnoughException(int code, String msg) {
        super();
        this.code = code;
        this.msg = 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;
    }
}

在实现类中进行测试打印

package cn.study;

public class ExceptionTest {
    public static void main(String[] args) {
        try {
            test();
        }catch (NullPointerException e){
            e.printStackTrace();
        }
        catch (UserNotEnoughException e) {
            int code = e.getCode();
            String msg = e.getMsg();
            e.printStackTrace();
            System.out.println(code+":"+msg);
        }
    }

    public static void test() throws UserNotEnoughException{
        throw new UserNotEnoughException(-1,"人员不够异常");
    }
}

image.png

throws / throw关键词

  • 简介: 讲解异常的抛出throw和声明throws
    • 代码出异常常⻅的处理⽅法
      • try catch捕获
      • throws 声明异常 往外抛出

语法:throws⼦句放在⽅法参数列表的右括号之后,⼀个⽅法可以声明抛出多个异常,多个异常之间⽤逗号隔开。


try catch中捕获了异常,处理⽅法,当前捕获⾃⼰处理,捕获⾃⼰处理然后继续往外⾯抛异常。