Java 自定义异常类模拟用户注册成功与失败
程序员文章站
2022-07-10 17:33:30
定义异常类public class RegisterException extends RuntimeException { private String msg; public String getMsg() { return msg; } public RegisterException(String msg) { super(msg);//将参数传递给父类,以方便调用父类方法 this.msg = msg;...
定义异常类
public class RegisterException extends RuntimeException {
private String msg;
public String getMsg() {
return msg;
}
public RegisterException(String msg) {
super(msg);//将参数传递给父类,以方便调用父类方法
this.msg = msg;
}
}
测试
public class Test {
private static String users[]={"aabb","aacc","aadd"};
public static void main(String[] args) {
String name="aabb";
try {
register(name);
System.out.println("注册成功");
}catch (RegisterException e){
// System.out.println(e.getMsg());//getMsg是自定义类中定义的方法
System.out.println(e.getMessage());//getMessage是父类RuntimesException的方法,如果想要使用此方法,需要在构造自定义类的时候将参数传递给父类,实现方式为super(msg)
}
}
public static boolean register(String name){
for (String user : users) {
if(user.equals(name)){
throw new RegisterException("注册失败,用户名已被占用");//传入参数给新创建的对象
}
}
return true;
}
}
本文地址:https://blog.csdn.net/e274426380/article/details/110289186
上一篇: java也有this,用法盘点