编写自定义异常类
public class IllegalNameException extends Exception{
public IllegalNameException(){
super();
}
public IllegalNameException(String s){
super(s);
}
}
编写用户服务类
public class UserService {
/*
* 用户注册
* username 用户名
* password 密码
*throws IllegelNameException 当用户名为Null。或者用户名才长度小于6,或者用户名长度大于14,会出现异常!
* */
public void register(String username,String password) throws IllegalNameException {
if(null==username||username.length()<6||username.length()>14){
throw new IllegalNameException("用户名有误,请重新输入");
}
System.out.println("注册成功,欢迎["+username+"]");
}
}
测试类
public class test {
public static void main(String[] args) {
UserService userService=new UserService();
//使用try catch捕获信息
try {
userService.register("jacksons","123");
} catch (IllegalNameException e) {
//输出异常信息或者成功信息
System.out.println(e.getMessage());
}
}
}