ジャワの国の新しい旅行記の11----異常で流れを制御します
5157 ワード
import java.util.HashMap;
import java.util.Map;
public class LoginService{
private Map<String,String> map;
public LoginService(){
map=new HashMap<String,String>();
map.put(" ", "123");
map.put(" ", "123");
map.put(" ", "123");
map.put(" ", "1234");
map.put(" ", "1234");
}
public boolean login(String name,String password) throws NoUserException,ErrorPswdException{
if(map.containsKey(name)){
String pswd=map.get(name);
if(pswd.equals(password)==false){
throw new ErrorPswdException(" "+name+" "+password);
}
}else{
throw new NoUserException("DB ");
}
return true;
}
public static void main(String[] args){
LoginService service=new LoginService();
String name=" 1";
String pswd="1235";
try{
boolean passed=service.login(name,pswd);
System.out.println(" "+name+" .");
}catch(NullPointerException e){
System.out.println(" , .");
}catch(NoUserException e){
System.out.println(" "+name+" , ");
}catch(ErrorPswdException e){
System.out.println(" "+name+" "+pswd+" , ");
}catch(Exception e){
e.printStackTrace();
}
}
}
2つの例外クラス:
public class ErrorPswdException extends Exception{
public ErrorPswdException(String msg){
super(msg);
}
}
public class NoUserException extends Exception{
public NoUserException(String msg){
super(msg);
}
}