반응형
사용자 정의 예외 클래스 구현
자바에서 제공되는 예외 클래스 이외에도 프로그래머가 직접 만들어야 하는 예외가 필요할 때가 있다
만들 때는 기존 예외 클래스 중 가장 유사한 예외 클래스에서 상속 받아 사용자 정의 예외 클래스를 만든다
기본적으로 Exception
클래스를 상속해서 만들 수 있다
패스워드에 대한 사용자 예외 클래스 만들기
패스워드를 입력할 때 다음과 같은 경우에 오류 처리를 한다
- 비밀번호는 null일 수 없다
- 비밀번호의 길이는 5 이상이다
- 비밀번호는 문자로만 이루어져서는 안된다(하나 이상의 숫자나 특수문자를 포함한다)
다음은 위 조건에 맞는 예시다
class PasswordException extends IllegalArgumentException {
public PasswordException(String message) {
super(message);
}
}
public class PasswordTest {
private String password;
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());
}
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
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;
}
}
실행결과는 다음과 같다
반응형
'Java' 카테고리의 다른 글
wait(), notify()를 활용한 동기화 (0) | 2024.08.29 |
---|---|
로그 남기기 (0) | 2024.08.26 |
예외 처리하기와 미루기 (0) | 2024.08.24 |
예외 처리 (0) | 2024.08.23 |
직렬화 (0) | 2024.08.23 |