IT/개발자 면접

Java Checked Exception과 Unchecked Exception

Collin 2023. 12. 12. 13:00
반응형

Java Checked Exception과 Unchecked Exception의 정의와 차이점:

  1. Checked Exception (Compile-time Exception):
    • 정의: 컴파일러에 의해 검사되고 처리가 강제되는 예외.
    • 예시: IOException, SQLException과 같이 입출력이나 데이터베이스와 관련된 예외들.
    • 처리 방법: 반드시 try-catch 블록이나 throws 키워드를 사용하여 예외 처리가 필요.
  2. Unchecked Exception (Runtime Exception):
    • 정의: 컴파일러가 검사하지 않고 런타임 시에 발생하는 예외.
    • 예시: NullPointerException, ArrayIndexOutOfBoundsException과 같이 프로그래머의 실수로 발생하는 예외들.
    • 처리 방법: 예외 처리 코드가 필요하지만, 강제적이지 않으며 생략 가능. 대부분의 경우 예외 처리보다는 예외가 발생하지 않도록 조치하는 것이 권장됨.

차이점 비교:

  1. 처리 여부:
    • Checked Exception: 반드시 예외 처리 코드가 필요.
    • Unchecked Exception: 예외 처리 코드가 필요하지만, 강제성은 없음.
  2. 검사 시점:
    • Checked Exception: 컴파일 시 예외가 검사됨.
    • Unchecked Exception: 런타임 시 예외가 검사됨.
  3. 발생 원인:
    • Checked Exception: 주로 외부 리소스와의 상호 작용에서 발생.
    • Unchecked Exception: 주로 프로그래머의 실수로 발생.
  4. 예시:
    • Checked Exception: IOException, SQLException.
    • Unchecked Exception: NullPointerException, ArrayIndexOutOfBoundsException.
  5. 처리 방법:
    • Checked Exception: try-catch 블록이나 throws 키워드 사용.
    • Unchecked Exception: 선택적인 예외 처리. 생략 가능.

 

  • Checked Exception과 Unchecked Exception은 모두 Exception 클래스를 상속받음.
  • Unchecked Exception은 RuntimeException 클래스를 상속받음.
// Checked Exception 처리
public void readFile() {
    try {
        // 파일 읽기 동작
    } catch (IOException e) {
        e.printStackTrace();
    }
}

// Unchecked Exception 처리 (생략 가능)
public void divide(int a, int b) {
    if (b != 0) {
        int result = a / b;
        System.out.println(result);
    }
}
반응형

'IT > 개발자 면접' 카테고리의 다른 글

마이크로서비스(Microservices)  (0) 2023.12.14
Git Flow 와 GitHub Flow , Branch 전략  (0) 2023.12.13
서비스 개발 요청을 받았을 때 업무 진행  (0) 2023.12.12
Spring Filter와 Interceptor  (0) 2023.12.11
Token과 Session  (0) 2023.12.10