异常链

异常链

一. 自定义一个登录与注册异常类继承父类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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值