异常链

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); //核心的代码
		}   
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值