自定义异常类
/*
自定义注册异常,继承RuntimeException
*/
public class RegistException extends RuntimeException {
// 定义无参构造方法
public RegistException() {
super();
}
// 定义有参构造方法
public RegistException(String message) {
super(message);
}
}
模拟注册时用户名已存在
public class Main {
public static void main(String[] args) {
// 即将要注册的用户名
String name = "username2";
// 数据库已有用户名
String[] usernames = {"username1", "username2", "username3"};
for (String username : usernames) {
if (name.equals(username)) {
throw new RegistException("用户名已存在");
}
}
System.out.println("注册成功");
}
}
运行结果