예외 클래스 계층 구조
Coddy Java 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 87개 중 59번째.
Java의 예외 처리 시스템은 Throwable 클래스를 루트로 하는 잘 구성된 클래스 계층 구조를 기반으로 합니다. 이 계층 구조를 이해하면 예외를 더 효과적으로 포착하고 처리할 수 있습니다.
맨 위에는 모든 예외와 오류의 부모인 Throwable이 있습니다. 여기에는 두 개의 직접적인 하위 클래스가 있습니다:
Throwable
├── Error // 심각한 문제 (이것들은 catch하지 마세요)
└── Exception // 복구 가능한 문제
└── RuntimeException // 비검사 예외Error는 애플리케이션이 처리하려고 해서는 안 되는 심각한 문제를 나타내며, OutOfMemoryError 또는 StackOverflowError와 같은 경우가 이에 해당합니다. 이러한 문제는 JVM 자체에 근본적인 문제가 있음을 나타냅니다.
Exception은 여러분이 가장 많이 다루게 될 분기입니다. 이는 두 가지 범주로 나뉩니다. checked 예외(Exception의 직접 하위 클래스)와 unchecked 예외(RuntimeException의 하위 클래스)입니다.
// 일반적인 예외 클래스
Exception
├── IOException // 파일/네트워크 문제
├── SQLException // 데이터베이스 문제
└── RuntimeException
├── NullPointerException
├── ArrayIndexOutOfBoundsException
└── IllegalArgumentExceptionexceptions는 classes이므로 상속 규칙을 따릅니다. parent 예외 유형을 포착하면 해당 유형의 모든 자식도 포착합니다:
try {
// 일부 코드
} catch (Exception e) {
// 모든 예외를 잡음 (보통 너무 광범위함)
}try {
// 일부 코드
} catch (RuntimeException e) {
// Catches only runtime exceptions and subclasses
}이 hierarchy를 사용하면 오류를 처리할 때 필요한 만큼 구체적이거나 일반적으로 지정할 수 있으며, 이는 나만의 사용자 지정 예외를 만드는 기반이 됩니다.
챌린지
쉬움Java의 exception hierarchy가 실제로 어떻게 작동하는지 보여 주는 exception analyzer를 만들어 봅시다! 다양한 specificity 수준에서 exception을 catch하고 어떤 type이 caught되었는지 보고하는 system을 만들게 됩니다.
code를 세 개의 file로 나누어 구성합니다:
ExceptionThrower.java: input에 따라 다양한 type의 exception을 trigger할 수 있는 class를 만듭니다. class에는 다음 세 개의 static method가 있어야 합니다:triggerRuntime(String type)- type string에 따라 서로 다른 runtime exception을 throw합니다:- type이
"null"이면NullPointerException을"Null value encountered"message와 함께 throw합니다 - type이
"index"이면ArrayIndexOutOfBoundsException을"Invalid index"message와 함께 throw합니다 - type이
"argument"이면IllegalArgumentException을"Bad argument"message와 함께 throw합니다
triggerArithmetic()-ArithmeticException을"Division error"message와 함께 throw합니다triggerGeneric()-IllegalStateException을"Generic runtime error"message와 함께 throw합니다 (해당 hierarchy는 Exception > RuntimeException > IllegalStateException입니다)- type이
ExceptionAnalyzer.java: 서로 다른 hierarchy 수준에서 exception을 catch하고 무엇이 caught되었는지 식별하는 class를 만듭니다. 다음 static method를 포함합니다:analyzeSpecific(String type)- try block 안에서ExceptionThrower.triggerRuntime(type)을 call합니다.NullPointerException,ArrayIndexOutOfBoundsException,IllegalArgumentException각각에 대해 별도의 catch block을 사용합니다. 각 경우에Caught specific: [exception class simple name]을 출력한 다음Message: [exception message]를 출력합니다analyzeWithParent()- try block 안에서ExceptionThrower.triggerArithmetic()를 call합니다.RuntimeException(parent type)을 사용하여 catch합니다.Caught via parent: RuntimeException을 출력한 다음Actual type: [exception class simple name]을 출력합니다analyzeWithGrandparent()- try block 안에서ExceptionThrower.triggerGeneric()을 call합니다. hierarchy에서 더 높은 위치에 있는Exception을 사용하여 catch합니다.Caught via grandparent: Exception을 출력한 다음Actual type: [exception class simple name]을 출력합니다Main.java: exception analyzer를 하나로 연결합니다! 하나의 input, 즉 exception type string을 받습니다("null","index","argument"중 하나).먼저
=== Specific Catch ===을 출력하고 input과 함께analyzeSpecific을 call합니다.그다음 blank line,
=== Parent Catch ===을 출력하고analyzeWithParent를 call합니다.마지막으로 blank line,
=== Grandparent Catch ===을 출력하고analyzeWithGrandparent를 call합니다.
trigger할 exception type으로 하나의 input을 받습니다("null", "index", "argument" 중 하나).
e.getClass().getSimpleName()을 사용하여 exception의 class name을 가져오고, e.getMessage()를 사용하여 그 message를 가져옵니다. 이 challenge는 parent exception type을 catch하면 모든 child도 함께 catch된다는 것을 보여 줍니다. 이는 exception handling을 얼마나 구체적으로 작성할지 결정할 때의 핵심 concept입니다!
직접 해보기
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String type = scanner.nextLine();
// TODO: Print "=== Specific Catch ===" and call ExceptionAnalyzer.analyzeSpecific(type)
// TODO: 빈 줄을 출력한 다음, "=== Parent Catch ==="를 출력한 후 ExceptionAnalyzer.analyzeWithParent()를 호출하세요
// TODO: Print a blank line, then "=== Grandparent Catch ===", then call ExceptionAnalyzer.analyzeWithGrandparent()
}
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
4상속
상속의 기초 (extends)super 키워드메서드 오버라이딩 (@Override)생성자 체이닝Object 클래스단일 및 다중 레벨 상속다중 클래스 상속이 불가능한 이유요약 - 직원 계층 구조직접 연습해 보세요: 온라인 Java 컴파일러