首页 > 其他 > 详细

自定义异常练习,代码演示

时间:2020-06-11 01:26:40      阅读:36      评论:0      收藏:0      [点我收藏+]

测试类

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * 步骤实现:
 *  1.自定义编译时异常:定义一个类继承Exception
 *  2.把构造方法生成
 *
 */
public class Demo01 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (true){
            System.out.println("请输入用户名:");
            String name = sc.next();
            System.out.println("请输入密码:");
            String password = sc.next();
            try {
                register(name,password);
                System.out.println("注册成功");
            } catch (RegisterException e) {
//                e.printStackTrace();

                System.out.println("注册出错了:"+e.getMessage());
            }
        }
    }

    public static boolean register(String name,String password) throws RegisterException {
        Map<String,String> accounts = new HashMap<>();
        accounts.put("Jack","123456");
        accounts.put("Rose","123456");
        //1.判断名字是否存在
        if(accounts.containsKey(name)){
            throw new RegisterException("账号已被注册,请更换!");
        }
        //2.密码是否合法6位
        if(password==null || password.length()!=6){
            throw new RegisterException("密码不规范");
        }

        accounts.put(name,password);

        System.out.println("accounts = " + accounts);
        return true;
    }
}

异常类

class RegisterException extends Exception{
    public RegisterException() {
    }

    public RegisterException(String message) {
        super(message);
    }

    public RegisterException(String message, Throwable cause) {
        super(message, cause);
    }

    public RegisterException(Throwable cause) {
        super(cause);
    }

    public RegisterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

自定义异常练习,代码演示

原文:https://www.cnblogs.com/liqiliang1437/p/13089283.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!