• Java之自定义异常·13


    • 为什么要使用自定义异常
      • 当前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, "人员不够异常");
        }
    }
    Bug? 不存在的!
  • 相关阅读:
    Chrome浏览器二维码生成插件
    《零成本实现Web性能测试:基于Apache JMeter》读书笔记
    《软件性能测试过程详解与案例剖析》读书笔记
    Python-Web-数据库-mongodb
    JAVA并发-基于AQS实现自己的显示锁
    FutureTask原理解析
    Linux上安装jdk,mysql
    Linux常用命令
    函数
    1.初识代码审计-基础
  • 原文地址:https://www.cnblogs.com/mrchenyushen/p/15422712.html
Copyright © 2020-2023  润新知