1定义
A方法声明了A异常,B方法捕获A异常(设A方法返回值为Boolean,true 无异常,false有异常。catch捕捉类型为A异常类型,throw抛出异常的原因参数设为A异常类型的对象)并声明B异常。
测试类里调用B方法捕获B异常(catch捕捉类型为B异常类型)
异常链创建了新的异常并保留了原有异常信息(让原有异常对象做新异常抛出异常的原因参数)
package Exception;
public class LogonFaildException extends Exception{
public LogonFaildException(){}
public LogonFaildException(String message){
super(message);
}
public LogonFaildException(Throwable cause){
super(cause);
}
public LogonFaildException(String message,Throwable cause){
super(message,cause);
}
}
package Exception;
public class RegisterFaildException extends Exception{
public RegisterFaildException(){};
public RegisterFaildException(String message){
super(message);
};
public RegisterFaildException(Throwable cause){
super(cause);
};
public RegisterFaildException(String message,Throwable cause){
super(message,cause);
};
}
package Exception;
public class User {
private String name;
private String password;
private int age;
private int phone;
private String city;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getPhone() {
return phone;
}
public void setPhone(int phone) {
this.phone = phone;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
package Exception;
public class Fangfa {
public static void main(String[] args) {
User user=new User();
try {
logon(user);
} catch (LogonFaildException e) {
e.printStackTrace();
}
}
//注册
public static boolean register(User user) throws RegisterFaildException{
boolean flag=false;
if(user.getName()==null){
if(!flag){
throw new RegisterFaildException("身份信息有误");
}else{return true;}
}else if(user.getPassword()==null){
return false;
}
return true;
}
//登录
public static void logon(User user) throws LogonFaildException{
try {
boolean register = register(user);
} catch (RegisterFaildException e) {
e.printStackTrace();
throw new LogonFaildException("登录失败", e); //核心的代码
}
}
}