自定义异常

  1. 自定义异常类

    • 当java提供给我们的异常类不够使用的时候就需要自定义异常类

    • 自定义异常类的格式

    • 格式:public class CustomException extends [Exception|RuntimeException]{

      ​ 添加一个空参构造方法

      ​ 添加一个异常信息的构造方法

      }

    • 自定义异常类必须要继承[Exception|RuntimeException]

    public class CustomException extends RuntimeException{
    
        public CustomException() {
        }
    
        public CustomException(String message) {
            super(message);
        }
    }
    
  2. 测试demo

public class Register {
    private static  String[] names={"cherish","cherish1","cherish2"};
    public static void main(String[] args) {
        //调用自定义的方法
        try{
            checkUsername("cherish");
            System.out.println("恭喜你,id未被注册");
        }catch (CustomException e){
            e.printStackTrace();
        }
    }

    public static boolean checkUsername(String uname){
        for (String name : names){
            if (name.equals(uname)){
                throw new CustomException("id已被注册");
            }
        }
        return true;
    }
}

努力学习java的Cherish
原文地址:https://www.cnblogs.com/cherish-code/p/14119592.html