测试类
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