二十四、Java基础之自定义异常

需求:用户名密码注册,用户名不得少于6位字符,否则提示:姓名不能少于6位!

/*
1.自定义无效名字异常:
1.编译时异常,直接继承Exception
2.运行时异常,直接继承RuntimeException

*/

public class IllegalNameException extends Exception{//编译时异常
//public class TestName06 extends RuntimeException{//运行时异常
    //定义异常一般提供两个构造方法
    public IllegalNameException(){}

    public IllegalNameException(String msg){
        super(msg);
    }


}

2.用户注册

/*
用户注册
 */

public class CustomerSercvices {

    public void Register(String name) throws IllegalNameException{

        //注册异常
        if(name.length()<6){
            //IllegalNameException ine=new IllegalNameException("姓名不能小于6位");
            //throw ine;
            throw new IllegalNameException("姓名不能小于6位!");
        }
        //完成注册
        System.out.println("注册成功!");

    }
}

3.测试程序

public class Test {

    public static void main(String[] args){

        String username="jack";
        CustomerSercvices cs=new CustomerSercvices();
        try{
            cs.Register(username);
        }catch(IllegalNameException e){
            System.out.println(e.getMessage());//姓名不能小于6位!
        }
    }
}
原文地址:https://www.cnblogs.com/chushujin/p/10160635.html