백엔드/Java

Java 예외 처리 실습

짱뚱짱 2024. 10. 20. 09:00

🔷 실습 1

- 사용자가 지정한 크기와 랜덤 숫자의 범위에 따라 배열을 생성.

- 만약 잘못된 입력이 들어오면 예외를 발생시켜서 프로그램이 정상적으로 동작하지 않도록 하고, 그에 대한 에러 메시지를 출력.

- 메서드 생성 기능 : size를 입력받아(매개변수) size 만큼의 길이를 가지는 배열을 생성하여 랜덤값을 채워 배열을 리턴 랜덤값은 범위를 매개변수를 받아 start(시작값), count(개수) - size가 0보다 작으면 예외발생 - 랜덤값의 개수가 0이면 예외발생

- 메서드 기능 : 매개변수로 배열을 받아 랜덤값을 채우는 메서드 랜덤값은 범위를 매개변수를 받아 start(시작값), count(개수) - 랜덤값의 개수가 0이면 예외발생 - 배열이 null이면 예외 발생 - 배열의 길이가 0보다 작으면 예외발생

package day07;

import java.util.Random;

public class ExceptionEx01 {

	public static void main(String[] args) {
		// 리턴 받은 배열을 출력
		try {
            int size = -1; 
            int start = 1; 
            int count = 10; 
            int[] arr = createArr(size, start, count);
            for (int num : arr) {
                System.out.print(num+" ");
            }
        } catch (RuntimeException e) {
        	e.printStackTrace();
            System.out.println(e.getMessage());
        }

	}

	public static int createRanNum(int start, int count) {
		return new Random().nextInt(count)+start;
	}

	public static int[] createArr(int size, int start, int count) {
		if (size < 0) {
			throw new RuntimeException("size가 0보다 작습니다.");
		}
		if (count <= 0) {
			throw new RuntimeException("랜덤값의 개수가 0입니다.");
		}
		int arr[] = new int[size];
		fillArrRanNum(arr, start, count);
		return arr;
	}

	public static void fillArrRanNum(int[] arr, int start, int count) {
		if(arr==null) {
			throw new RuntimeException("배열이 null입니다.");
		}
		if(arr.length<0) {
			throw new RuntimeException("배열의 길이가 0보다 작습니다.");
		}
		if(count<=0) {
			throw new RuntimeException("랜덤값의 개수가 0입니다.");
		}

		for (int i=0; i<arr.length; i++) {
			//RuntimeException이 아닌 Checked Exception이었다면 이미 빨간밑줄
			arr[i] = createRanNum(start, count);
		}
	}
}

 

 

🔷 실습 2

- 비밀번호 검증기 => 비밀번호의 유효성을 검사

- 사용자 정의 Exception

  👉🏻 사용자가 직접 Exception 클래스 생성시
  👉🏻 IllegalArgumentException 클래스 상속
  👉🏻 메서드의 부적절한 인수를 사용자가 생성
  👉🏻 passwordException
    ❕ 비밀번호는 null일 수 없다.
    ❕ 비밀번호의 길이는 5자 이상
    ❕ 비밀번호는 문자로만 이루어지면 안됨.(숫+문, 문+특+숫)

 

 

비밀번호 관련 예외 처리를 위한 PasswordException 클래스 생성

package day07;

public class PasswordException extends IllegalArgumentException {
    private static final long serialVersionUID = 1L;

    public PasswordException(String message) {
        super(message);
    }
}

 

 

비밀번호를 검증하는 PasswordTest 클래스

package day07;

class PasswordTest {
    private String password;

    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;
    }
}

 

 

예외 처리 테스트

public class ExceptionEx02 {
    public static void main(String[] args) {
        PasswordTest pt = new PasswordTest();
        String password = null; // 다른 값을 주어 테스트가능
//      String password = "abc";
//		String password = "abcdef";
//		String password = "abcdef01";

        try {
            pt.setPassword(password);
            System.out.println(pt.getPassword());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

 

결과

day07.PasswordException: 비밀번호는 null일 수 없습니다.
	at java_project/day07.PasswordTest.setPassword(ExceptionEx02.java:13)
	at java_project/day07.ExceptionEx02.main(ExceptionEx02.java:34)

 

 


예외는 오류의 언어, 처리는 그 언어를 이해하는 지혜의 열쇠다.

 

'백엔드 > Java' 카테고리의 다른 글

Java Collection 프레임워크  (1) 2024.10.20
Java 익명 클래스(Anonymous Class)  (0) 2024.10.20
Java 예외 처리  (0) 2024.10.17
Java 날짜와 시간  (0) 2024.10.16
Java로 고객 관리 시스템 구현  (2) 2024.10.15