사용자 정의 예외 처리 (패스워드)

Codren·2021년 6월 5일

Section 1. 사용자 정의 예외 처리

1. 사용자 정의 예외 처리

  • 원하는 예외 처리가 자바에서 제공되지 않을 때 직접 예외 처리를 정의
  • 언제 예외가 발생될지 사용자가 지정할 수 있음
  • 기존 예외 클래스 중 가장 유사한 예외 클래스에서 상속 받거나 Exception 상속




2. 패스워드에 대한 예외 처리

  • 비밀번호는 null 을 허용하지 않는다
  • 비밀번호의 길이는 5 이상으로 한다
  • 비밀번호는 문자로만 이루어져서는 안된다 (하나이상의 숫자나 특수문자를 포함)




3. 사용자 정의 예외

  • 하위 클래스 PasswordException 이 생성 되기 전에 상위 클래스 Exception 이 먼저 생성됨
  • Exception 생성자를 호출할 때 super(String message) 생성자 호출
  • 하위 클래스 PasswordException 에서 아무런 초기화를 해주지 않는다면 하위 클래스는 상위 클래스의 모든 값을 동일하게 가짐
  • 사용자 정의 예외 클래스
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());
          }
      }
    }

0개의 댓글