본문 바로가기
  • Let's study
알고리즘/Java

[Java] try-catch

by 코딩고수이고파 2026. 7. 21.

try-catch

try-catch는 프로그램 실행 중 발생할 수 있는 예외(Exception)를 처리하여 프로그램이 비정상적으로 종료되지 않도록 하는 문법이다.

try

예외가 발생할 가능성이 있는 코드를 try 블록 안에 작성한다.

 

try {
    int[] arr = new int[3];
    arr[4] = 10;
}

 

예외가 발생하지 않으면 catch는 실행되지 않는다.

catch

catch는 발생한 예외를 처리하는 영역이다.

 

catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("배열 관련 예외 발생");
}

 

예외 객체는 e 변수로 전달되며, 예외에 맞는 catch 블록이 실행된다.

여러 개의 catch 사용

발생 가능한 예외마다 catch를 여러 개 작성할 수 있다.

 

try {
    int[] arr = new int[3];
    arr[4] = 10;

    String str = "la";
    int rst = Integer.parseInt(str);
}
catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("배열 관련 예외 발생");
}
catch (NumberFormatException e) {
    System.out.println("숫자 변환 관련 예외 발생");
}
catch (Exception e) {
    System.out.println("기타 예외 발생");
}
 

위 코드에서는

 

  • 배열 범위를 벗어나면 ArrayIndexOutOfBoundsException
  • 숫자로 변환할 수 없는 문자열이면 NumberFormatException
  • 그 외의 예외는 Exception에서 처리한다.

catch 작성 순서

예외는 구체적인 예외부터 부모 예외 순서로 작성해야 한다.

 

catch (ArrayIndexOutOfBoundsException e) { }

catch (NumberFormatException e) { }

catch (Exception e) { }
 

Exception은 대부분의 예외의 부모 클래스이므로 가장 마지막에 작성해야 한다.

자주 사용하는 예외 종류

예외발생  상황
ArrayIndexOutOfBoundsException 배열의 범위를 벗어난 인덱스에 접근했을 때
NumberFormatException 숫자로 변환할 수 없는 문자열을 숫자로 변환하려고 했을 때
NullPointerException null인 객체의 메서드나 필드에 접근했을 때
ArithmeticException 0으로 나누는 등 산술 연산 오류가 발생했을 때
ClassCastException 잘못된 형변환을 했을 때
StringIndexOutOfBoundsException 문자열의 범위를 벗어난 인덱스에 접근했을 때
InputMismatchException Scanner 등에서 입력 타입이 맞지 않을 때
IllegalArgumentException 메서드에 잘못된 인자를 전달했을 때
IOException 파일 입출력 등 I/O 작업 중 오류가 발생했을 때
Exception 대부분의 예외의 부모 클래스

댓글