Computer Science/Java

[JAVA] 예외가 터지면 코드 흐름은 어떻게 될까

GWDEVEL 2026. 2. 13. 20:34

[JAVA] 예외가 터지면 코드 흐름은 어떻게 될까

자바에서 예외(Exception)를 처음 배울 때 문법 자체보다 더 헷갈렸던 건 “예외가 발생하면 코드가 어디까지 실행되는가”였다. 이 글은 예외가 발생했을 때 프로그램의 흐름이 어떻게 바뀌는지를 정리한 내용이다.


1. 예외가 발생하면 어떻게 될까

System.out.println("A");
int x = 10 / 0;
System.out.println("B");

위 코드에서 10 / 0 부분에서 예외가 발생한다. 출력 결과는 A까지만 출력되고, 그 아래 코드는 실행되지 않는다.

예외가 발생한 순간, 현재 실행 흐름은 즉시 중단된다.


2. try-catch가 없는 경우

예외를 처리하지 않으면 JVM은 예외 정보를 출력하고 프로그램을 종료시킨다.

int n = Integer.parseInt("abc");

컴파일은 되지만, 실행 중 NumberFormatException이 발생하며 종료된다.


3. try-catch가 있는 경우

try {
    System.out.println("A");
    int x = 10 / 0;
    System.out.println("B");
} catch (ArithmeticException e) {
    System.out.println("C");
}
System.out.println("D");

실행 흐름은 다음과 같다.

  1. A 출력
  2. 예외 발생
  3. try 블록 중단
  4. catch 블록 실행 (C 출력)
  5. try-catch 이후 코드 실행 (D 출력)

예외가 발생해도 catch에서 처리되면 프로그램은 계속 실행된다.


4. catch는 아무 예외나 잡지 않는다

try {
    String s = null;
    System.out.println(s.length());
} catch (ArithmeticException e) {
    System.out.println("산술 예외");
}
System.out.println("끝");

위 코드는 NullPointerException이 발생하지만, catch는 ArithmeticException만 처리하도록 되어 있다.

결과적으로 예외는 잡히지 않고 프로그램은 종료된다.


5. 다중 catch 흐름

try {
    String s = null;
    System.out.println(s.length());
} catch (NullPointerException e) {
    System.out.println("null 접근");
} catch (Exception e) {
    System.out.println("기타 예외");
}
System.out.println("정상 종료");

구체적인 예외부터 위에 작성해야 하며, 해당 예외가 잡히면 아래 catch는 실행되지 않는다.


6. finally는 언제 실행될까

try {
    System.out.println("try");
    int x = 10 / 0;
} catch (Exception e) {
    System.out.println("catch");
} finally {
    System.out.println("finally");
}
System.out.println("end");

출력 순서는 다음과 같다.

try
catch
finally
end

finally는 예외 발생 여부와 상관없이 실행된다.


7. return이 있어도 finally는 실행된다

static int test() {
    try {
        return 1;
    } finally {
        System.out.println("finally 실행");
    }
}

메서드가 return을 만나도 finally 블록은 실행된 뒤 반환된다.


8. 예외를 던지면 흐름은 어떻게 될까

static void run() throws Exception {
    System.out.println("A");
    throw new Exception();
}
try {
    run();
    System.out.println("B");
} catch (Exception e) {
    System.out.println("C");
}
System.out.println("D");

run() 안에서 예외가 발생하면 호출한 쪽으로 예외가 전달된다.

출력 결과는 A → C → D 순서다.


9. 예외 흐름 한 줄 요약

  • 예외 발생 시 현재 흐름 즉시 중단
  • try 안에서 발생하면 catch로 이동
  • catch에서 처리되면 이후 코드 계속 실행
  • finally는 항상 실행

정리

  • 예외는 코드 흐름을 강제로 변경한다.
  • try 이후 코드는 예외 발생 시 실행되지 않는다.
  • catch는 해당 예외 타입만 처리한다.
  • finally는 흐름과 상관없이 실행된다.