Java 自定义异常类【实现用户登录】

实际场景中,一些情况需要我们对异常类进行扩展,创建符合实际情况的异常,比如实现用户登录功能时,当出现用户名和密码错误时,需要我们自己抛出异常。

//    public static void login(String username, String password){
//        if(!TestDemo.username.equals(username)){
//            //处理用户名错误
//        }
//        if(!TestDemo.password.equals(password)){
//            //处理错误密码
//        }
//        System.out.println("登录成功!");
//    }
//
//    public static void main(String[] args) {
//        login("admin","123456");
//	  }


/*
自定义异常类
当我们处理用户名以及密码错误时需要抛出两种异常,我们可以基于已有的异常类进行扩展或者说继承,主动创建业务相关的类
 */
class UserError extends Exception {
    public UserError(String message) {
        super(message);
    }
}
    
class PasswordError extends Exception {
    public PasswordError(String message) {
        super(message);
    }
}

public class TestDemo {
    private static String username = "admin";
    private static String password = "123456";

    public  void login(String userName, String passWord) throws UserError, PasswordError{
        if(!TestDemo.username.equals(userName)){
            throw new UserError("用户名错误!");
        }
        if(!TestDemo.password.equals(passWord)){
            throw new PasswordError("密码错误!");
        }
        System.out.println("登录成功!");
    }

    //这时我们可以将login改成如下形式:
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        while(sc.hasNextLine()){
            String name = sc.nextLine();
            String num = sc.nextLine();

        try {
            TestDemo test = new TestDemo();
            test.login(name, num);
        } catch (UserError userError) {
            userError.printStackTrace();
        } catch (PasswordError passwordError) {
            passwordError.printStackTrace();
        }

        }
    }

}

在这里插入图片描述
此外需要注意的是:
1.自定义异常类通常继承Exception或者RuntimeException
2.继承Exception的异常默认为受查异常
2.继承RuntimeException的异常默认为非受查异常

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值