异常链
一. 自定义一个登录与注册异常类继承父类Exception,重写父类构造方法
public class LoginFaildException extends Exception {
public LoginFaildException() {
super();
}
public LoginFaildException(String message, Throwable cause) {
super(message, cause);
}
public LoginFaildException(String message) {
super(message);
}
public LoginFaildException(Throwable cause) {
super(cause);
}
二.定义用户类,声明用户名与密码,添加构造方法
public class User {
private String userName;
private String passWord;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
三.声明注册与登录方法
// 注册方法
public static boolean register(User user) throws RegisterException { //声明一个返回值为布尔类型的方法
boolean flag = false; //声明返回值变量
if (user.getUserName() == null) {
if (!flag) {
throw new RegisterException("用户名不能为空,注册失败"); //抛出注册异常
} else {
return true;
}
}else if(user.getPassWord().equals(null)){
return false;
}
return true;
}
// 登录方法
public static void login(User user) throws LoginFaildException {
try {
boolean register= register(user);
} catch (RegisterException e) {
e.printStackTrace();
throw new LoginFaildException("登录失败",e); //核心代码,将注册与登录异常抛给登录异常构造方法
}
}
四.在main方法中调用登录方法
public static void main(String[] args) {
User user = new User();
try {
login(user);
} catch (LoginFaildException e) {
e.printStackTrace(); //抛出异常
}
运行结果如下:
exception.RegisterException: 用户名不能为空,注册失败
at test.Test4.register(Test4.java:23)
at test.Test4.login(Test4.java:36)
at test.Test4.main(Test4.java:12)
exception.LoginFaildException: 登录失败
at test.Test4.login(Test4.java:40)
at test.Test4.main(Test4.java:12)
Caused by: exception.RegisterException: 用户名不能为空,注册失败
at test.Test4.register(Test4.java:23)
at test.Test4.login(Test4.java:36)
... 1 more