1. 사용자 정의 예외 처리
2. 패스워드에 대한 예외 처리
3. 사용자 정의 예외
public class PasswordException extends Exception{
public PasswordException(String message) {
super(message); # PasswordException 인스턴스를 생성하기 전에
} # super(message) 생성자로 Exception 인스턴스 생성
}
public class PasswordTest {
private String password;
public String getPassword(){
return password;
}
public void setPassword(String password) throws PasswordException{ # 예외 미루기
if(password == null){
throw new PasswordException("비밀번호는 null 일 수 없습니다"); # 예외 발생
}
else if( password.length() < 5){
throw new PasswordException("비밀번호는 5자 이상이어야 합니다."); # 예외 발생
}
else if (password.matches("[a-zA-Z]+")){ # 정규표현식
throw new PasswordException("비밀번호는 숫자나 특수문자를 포함해야 합니다."); # 예외 발생
}
this.password = password;
}
# main 부분
public static void main(String[] args) {
PasswordTest test = new PasswordTest(); # 예외가 발생할 수 있는 클래스를 생성
String password = null;
try {
test.setPassword(password);
System.out.println("오류 없음1");
} catch (PasswordException e) {
System.out.println(e.getMessage());
}
password = "abcd";
try {
test.setPassword(password);
System.out.println("오류 없음2");
} catch (PasswordException e) {
System.out.println(e.getMessage());
}
password = "abcde";
try {
test.setPassword(password);
System.out.println("오류 없음3");
} catch (PasswordException e) {
System.out.println(e.getMessage());
}
password = "abcde#1";
try {
test.setPassword(password);
System.out.println("오류 없음4");
} catch (PasswordException e) {
System.out.println(e.getMessage());
}
}
}