在代码中使用自定义的异常类,可以对异常进行统一的封装处理。使得整个项目的异常处理更规范、更统一、更优雅。同时,使得日志的记录上更加清晰,便于后续查日志定位问题。

  以下为自定义异常类的完整过程:

1、需要自定义一个类,继承自系统的异常类。具体需要什么样类型的异常类,就继承自相应的系统类。

      如果希望写一个检查性异常类,则需要继承 Exception 类。

      如果你想写一个运行时异常类,那么需要继承 RuntimeException 类。

/**
 * @Auther: admin
 * @Date: 2018/12/16 14:40
 * @De ion:自定义异常类
 */
public class CustomException extends RuntimeException{
    private String code;
    public CustomException() {
        super();
    }
    public CustomException(String message) {
        super(message);
    }
    public CustomException(String code, String message) {
        super(message);
        this.code = code;
    }
    public String getCode() {
        return this.code;
    }
}

2、在需要抛出该异常的类或方法中,定义当出现异常时抛出自定义的异常。

if (Info == null) {
throw new CustomException(\"Info不能为空\");
}

 

收藏 打印