java

31. 자바의 예외 처리 방법-3(사용자 정의 예외)

dalc3154 2025. 3. 5. 17:31

사용자 정의 예외

자바의 Exception 클래스를 상속받는 자식 클래스를 직접 정의

 

예시)

class InvalidUserException extends Exception {
	InvalidUserException(String message) {
		super(message);// Exception 클래스의 getMessage()에서 사용
	}
}

class CustomException extends Exception {
	CustomException(String message) {
		super(message);
	}
}
public class Exception03 {
	
	// 단일 예외 던지기(throws)
	// 메소드 선언부에서 해당 메소드가 발생시킬 수 있는 예외를 명시하는 키워드
	static void login(String username, String password) throws InvalidUserException {
		// 문자열.equals(문자열);
		// 동일한 문자열일 경우 true, 아니면 false 반환
		if(!"admin".equals(username)) {
			// 잘못된 사용자인 경우
			throw new InvalidUserException("사용자 이름이 잘못되었습니다");
		}
	}
	
	// 여러 예외 던지기
	// throws 키워드에 ,(콤마)로 구분하여 나열
	static void exceptions(int num) throws CustomException, ArithmeticException, ArrayIndexOutOfBoundsException {
		if(num == 1) {
			throw new CustomException("1번 선택 - 커스텀 예외");
		} else if(num == 2) {
			throw new ArithmeticException("2번 선택 - 수학 공식 예외");
		} else {
			throw new ArrayIndexOutOfBoundsException("그 외: 배열 인덱스 초과 예외");
		}
	}
	
	public static void main(String[] args) {
		int age = -10;
		
		try {
			if (age < 0) {
				throw new Exception("나이는 음수가 될 수 없습니다");
				
			}
			System.out.println("출력 x");
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		// 사용자 정의 예외
		// InvalidUserException
		
		//login("admin", "password");
		// throws로 메소드의 예외 발생 가능성을 명시하는 경우
		// 메소드 호출 시 반드시 try-catch 블록의 예외 처리가 필수
		try {
			login("admin", "password");
		} catch (InvalidUserException e) {
			System.out.println(e.getMessage());
		}
		
		// 여러 예외 던지기
		try {
			System.out.println("여러 예외 던지기 테스트");
			exceptions(3);
		} catch(CustomException e) {
			System.out.println("1번: " + e.getMessage());
		} catch(ArithmeticException e) {
			System.out.println("2번: " + e.getMessage());
		} catch(ArrayIndexOutOfBoundsException e) {
			System.out.println("기타: " + e.getMessage());
		}
		
	}
}

'java' 카테고리의 다른 글

33. API-java.lang  (0) 2025.03.05
32. API  (0) 2025.03.05
29. 자바의 예외 처리 방법-1(try-catch)  (0) 2025.03.05
28. 예외(Exception)  (0) 2025.03.05
실습) 추상 클래스 활용2  (0) 2025.02.27