Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

사용자 정의 예외 클래스 활용 본문

Java/다양한 기능

사용자 정의 예외 클래스 활용

Seung__ 2021. 10. 31. 11:07

1. 사용자 정의 예외 클래스 구현


  • 자바에서 제공되는 예외 클래스 외에 직접 만들어야 하는 예외가 있을 수  있음
  • 기존 예외 클래스 중 가장 유사한 예외 클래스에서 상속받아 사용자 정의 예외 클래스 생성
  • 기본적으로 Exception 클래스를 상속해서 만들 수 있음.

 

2. 예) password에 대한 예외 처리


  • 패스워드를 입력할 때 다음과 같은 경우 오류처리
    • 비밀번호 null
    • 비밀번호 길이 5 미만
    • 비밀번호가 문자로만 이루어진 경우(특수 문자 포함해야 함)
public class PasswordTest {

    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {

        if (password == null) {
            throw new PasswordException("비밀번호는 필수");
        }else if (password.length() < 5){
            throw new PasswordException("비밀번호는 5자 이상");
        }else if (password.matches("[a-zA-Z]+")){
            throw new PasswordException("비밀번호는 숫자나 특수문자 포함해야 함");
        }
        this.password = password;
    }

    public static void main(String[] args) {

        PasswordTest test = new PasswordTest();

        String pw1 = null;
        try{
            test.setPassword(pw1);
        }catch (PasswordException e){
            System.out.println(e.getMessage());
        }

        String pw2 = "abc";
        try{
            test.setPassword(pw2);
        }catch (PasswordException e){
            System.out.println(e.getMessage());
        }

        String pw3 = "abcasdf";
        try{
            test.setPassword(pw3);
        }catch (PasswordException e){
            System.out.println(e.getMessage());
        }

        String pw4 = "abc21!";
        try{
            test.setPassword(pw4);
            System.out.println("성공");
        }catch (PasswordException e){
            System.out.println(e.getMessage());
        }
    }
}

 

 

 

3. GitHub : 211031 custom Exception


 

GitHub - bsh6463/various_functions

Contribute to bsh6463/various_functions development by creating an account on GitHub.

github.com

 

'Java > 다양한 기능' 카테고리의 다른 글

표준 입출력 스트림  (0) 2021.10.31
자바 입출력을 위한 I/O Stream  (0) 2021.10.31
예외 처리와 미루기  (0) 2021.10.30
예외 처리  (0) 2021.10.29
Stream활용 예시  (0) 2021.10.29
Comments