Menu
Coddy logo textTech

Checked vs Unchecked 에러

Coddy Java 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 87개 중 61번째.

Java의 예외 계층 구조가 여러 분기로 나뉜다는 것을 살펴보았습니다. 이해해야 할 핵심적인 구분은 checked 예외와 unchecked 예외의 차이입니다. 이는 코드에서 예외를 처리해야 하는 방식에 영향을 줍니다.

Checked exceptions는 컴파일러가 사용자가 handle하도록 강제하는 예외입니다. RuntimeException을 거치지 않고 Exception을 직접 확장합니다. 이를 catch하거나 throws를 사용하여 선언해야 합니다.

// IOException을 반드시 처리해야 함 - 체크 예외임
public void readFile(String path) throws IOException {
    FileReader reader = new FileReader(path);  // IOException을 던질 수 있음
}

// 또는 잡아서 처리
public void readFileSafe(String path) {
    try {
        FileReader reader = new FileReader(path);
    } catch (IOException e) {
        System.out.println("File error: " + e.getMessage());
    }
}

검사되지 않은 exceptionsRuntimeException을 확장합니다. 컴파일러는 이를 handle하도록 요구하지 않습니다. 일반적으로 null 참조나 잘못된 배열 접근과 같은 프로그래밍 error를 나타냅니다:

// throws 선언이 필요 없음
public int divide(int a, int b) {
    return a / b;  // ArithmeticException을 던질 수 있음 (unchecked)
}

String name = null;
name.length();  // NullPointerException (unchecked)

사용자 지정 exceptions을 만들 때는 호출자가 이를 어떻게 처리하기를 원하는지에 따라 부모 class를 선택하세요. 호출자가 예상해야 하는 복구 가능한 조건에는 checked exceptions을 사용하세요. 올바른 코드에서는 발생해서는 안 되는 프로그래밍 오류에는 unchecked exceptions을 사용하세요.

challenge icon

챌린지

쉬움

checked 및 unchecked exception의 핵심 차이를 보여 주는 age verification system을 만들어 봅시다! 두 유형의 custom exception을 만들고 compiler가 이를 어떻게 다르게 처리하는지 확인하게 됩니다.

코드를 네 개의 파일로 구성합니다:

  • InvalidAgeException.java: age validation 실패를 위한 checked exception을 Create합니다. 이 exception은 Exception을 직접 extend해야 하며, 이는 Callers가 이를 handle하도록 FORCED된다는 의미입니다. message를 accepts하고 이를 parent class에 전달하는 constructor를 포함하세요.
  • NegativeAgeException.java: 누군가 음수 age를 제공했을 때를 위한 unchecked exception을 Create합니다(올바른 input에서는 발생하지 않아야 하는 programming error). RuntimeException을 extend해야 합니다. message를 accepts하고 parent에 전달하는 constructor를 포함하세요.
  • AgeVerifier.java: 두 exception type을 사용해 age를 검증하는 class를 Create합니다. 두 개의 static method를 포함하세요:

    verifyAge(int age) - age가 0보다 작으면 이 method는 NegativeAgeException(unchecked)을 "Age cannot be negative: [age]" message와 함께 throw해야 합니다. age가 18보다 작으면 InvalidAgeException(checked)을 "Must be 18 or older: [age]" message와 함께 throw하세요. 그렇지 않으면 Age [age] verified successfully를 print합니다. 이 method는 checked exception을 throw하므로 throws InvalidAgeException으로 declare해야 합니다.

    verifyAgeUncheckedOnly(int age) - 이 method는 unchecked exception만 사용합니다. age가 음수이면 같은 message 형식으로 NegativeAgeException을 throw합니다. age가 18보다 작으면 IllegalArgumentException"Too young: [age]" message와 함께 throw합니다. 그렇지 않으면 Age [age] verified (unchecked method)를 print합니다. 이 method에는 throws declaration이 필요하지 않다는 점에 주의하세요!

  • Main.java: verification system을 하나로 결합합니다! 하나의 input, 즉 age(integer)를 받습니다.

    먼저 === Checked Exception Method ===를 print하고 input age와 함께 verifyAge를 Call합니다. 이 method는 checked exception을 throw하므로 try-catch로 감싸야 합니다. InvalidAgeException을 catch하고 Checked exception caught: [message]를 print합니다. 또한 NegativeAgeException을 catch하고 Unchecked exception caught: [message]를 print합니다.

    그런 다음 빈 줄과 === Unchecked Exception Method ===를 print합니다. 같은 age와 함께 verifyAgeUncheckedOnly를 Call합니다. 이 method가 exception을 throw할 수 있더라도 이를 catch하도록 FORCED되지는 않습니다. 하지만 error를 우아하게 handle하기 위해 try-catch로 감싸세요. NegativeAgeException을 catch하고 Runtime exception caught: [message]를 print합니다. IllegalArgumentException을 catch하고 Illegal argument caught: [message]를 print합니다.

검증할 age를 나타내는 integer인 하나의 input을 받습니다.

핵심 차이에 주목하세요. checked exception을 사용하는 method는 requires a throws declaration이며 Callers가 이를 handle하도록 FORCES하지만, unchecked method는 어떤 exception handling도 없이 정상적으로 compile됩니다. 이것이 Java에서 checked와 unchecked exception 사이의 fundamental distinction입니다!

직접 해보기

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int age = scanner.nextInt();
        
        // TODO: Test the checked exception method
        // Print: "=== Checked Exception Method ==="
        // try-catch 문에서 AgeVerifier.verifyAge(age) 호출
        // - Catch InvalidAgeException: print "Checked exception caught: [message]"
        // - Catch NegativeAgeException: print "Unchecked exception caught: [message]"
        
        
        // TODO: Print a blank line, then "=== Unchecked Exception Method ==="
        // try-catch 문에서 AgeVerifier.verifyAgeUncheckedOnly(age) 호출
        // - Catch NegativeAgeException: print "Runtime exception caught: [message]"
        // - Catch IllegalArgumentException: print "Illegal argument caught: [message]"
        
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 Java 컴파일러