java异常及自定义异常

100 阅读1分钟

Throwable分为

Error

程序无法处理,通常指程序中出现的严重问题
Error是不可查的,因此当Error(错误)出现时,程序会立即崩溃,Java虚拟机立即停止运行
栈溢出错误 内存溢出

Exception

指程序本身可以处理的异常,可以向上抛出或者捕获处理
分为受检异常与非受检异常

受检异常 (编译异常)

所有的继承Exception的异常,除了RuntimeException

  • IOException
  • SQlException
  • ClassNotFoundException
  • TimeOutException
  • NoSuchMethodException等

非受检异常(运行时异常)

RuntimeException以及继承了RuntimeException的异常类

自定义受检异常

继承Exception

自定义非受检异常

继承RuntimeException 或继承 继承了RuntimeException的异常类

@Setter
@Getter
public class BaseException extends RuntimeException {

   private static final long serialVersionUID = 1509003019001L;

    private Integer code;

    public BaseException(String message) {
        super(message);
        this.code = ResponseCodeEnum.SERVICE_ERROR.getCode();
    }

    public BaseException(String message, Throwable t) {
        super(message, t);
        this.code = ResponseCodeEnum.SERVICE_ERROR.getCode();
    }

    public BaseException(Integer code, String message) {
        super(message);
        this.code = code;
    }

//    Throwable t  用来传递其他异常的信息或者引起当前异常的根本原因
    public BaseException(Integer code, String message, Throwable t) {
        super(message, t);
        this.code = code;
    }