예외 던지기
Coddy Java 여정의 논리와 흐름 섹션에 포함된 레슨 — 59개 중 42번째.
Java의 throw 키워드는 예외를 명시적으로 발생시킬 수 있게 합니다. 기본 구조는 다음과 같습니다:
throw new ExceptionType("Error message");구성 요소는 다음과 같습니다:
throw: 예외를 던지는 키워드new ExceptionType: 새로운 예외를 생성합니다 (예: IllegalArgumentException)"Error message": 잘못된 점을 설명합니다
실제로 동작하는 모습을 확인해 보겠습니다:
int age = -5;
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}위의 코드를 실행한 후, 프로그램은 다음 예외를 발생시킵니다:
IllegalArgumentException: Age cannot be negative
챌린지
쉬움validateAge라는 이름을 가진 메서드를 생성하세요. 이 메서드는 두 개의 인수를 받습니다:
- 검증할 정수 (
age) - 검증 규칙을 결정하는 불리언 (
strict)
이 메서드는 다음 규칙에 따라 예외를 발생시켜야 합니다:
- age가 음수인 경우: 메시지 "Age cannot be negative"와 함께 IllegalArgumentException을 발생시키세요
- age가 150을 초과하는 경우: 메시지 "Age cannot be greater than 150"와 함께 IllegalArgumentException을 발생시키세요
- strict가 true이고 age가 0인 경우: 메시지 "Age cannot be zero in strict mode"와 함께 IllegalArgumentException을 발생시키세요
- 예외가 발생하지 않으면: age를 문자열로 반환하세요
치트 시트
throw 키워드를 사용하면 예외를 명시적으로 던질 수 있습니다:
throw new ExceptionType("Error message");구성 요소:
throw: 예외를 던지는 키워드new ExceptionType: 새 예외를 생성합니다 (예: IllegalArgumentException)"Error message": 무엇이 잘못되었는지 설명합니다
예제:
int age = -5;
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}직접 해보기
import java.util.Scanner;
public class Main {
public static String validateAge(int age, boolean strict) {
// 여기에 코드를 작성하세요
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int age = Integer.parseInt(scanner.nextLine());
boolean strict = Boolean.parseBoolean(scanner.nextLine());
try {
System.out.println(validateAge(age, strict));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.