topic난이도 · 약 18

예외 처리

`try` → 발생 시 해당 `catch` → 항상 `finally`. 자원 해제는 finally에서.

#Java#예외처리
왜 배우는가

try-catch-finally 실행 순서와 return 시점의 finally 실행 여부가 코드 추적 문제로 나온다.

java
public static int test() {
    try {
        System.out.println("try");
        return 1;
    } catch (Exception e) {
        System.out.println("catch");
        return 2;
    } finally {
        System.out.println("finally");
    }
}
// 호출: int r = test();
// 출력: try → finally
// r = 1  (return 직전에도 finally는 실행된다)

법칙: return이 있어도 finally는 실행된다. 단, finally에 return을 또 넣으면 try의 return을 덮어쓴다 — 절대 하지 말 것.

종류설명예시
Checked컴파일러가 처리 강제IOException, SQLException
Unchecked (RuntimeException)런타임에만 체크NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException
ErrorJVM 레벨, 복구 불가OutOfMemoryError, StackOverflowError
실기 드릴 1문항
code실기 드릴 · 코드 추적

다음 코드의 출력은?

java
public class Test {
    public static void main(String[] args) {
        try {
            int[] a = {1, 2, 3};
            System.out.print(a[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.print("IDX,");
        } catch (Exception e) {
            System.out.print("EXC,");
        } finally {
            System.out.print("END");
        }
    }
}