try, catch 예외처리에 대해

Gunju Kim·2025년 3월 26일
0

필수시청 영상

목록 보기
25/32

✅ 예외(Exception)란?

  • 프로그램 실행 중에 발생할 수 있는 오류 상황

  • 예: 0으로 나누기, 배열 인덱스 초과, null 접근, 파일 없음 등

예외가 발생하면 프로그램이 즉시 멈추고 비정상 종료될 수 있기 때문에
이를 방지하기 위해 try-catch 문으로 감싸서 예외를 처리합니다.

📌 try-catch 기본 구조 (Java)

try {
    // 예외가 발생할 수 있는 코드
} catch (예외타입 변수명) {
    // 예외가 발생했을 때 실행할 코드
}

✅ 예제 1: 0으로 나누는 경우

public class Example {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;  // 예외 발생 (ArithmeticException)
            System.out.println("결과: " + result);
        } catch (ArithmeticException e) {
            System.out.println("0으로 나눌 수 없습니다.");
        }

        System.out.println("프로그램 계속 실행됨");
    }
}

실행 결과

0으로 나눌 수 없습니다.
프로그램 계속 실행됨

✅ 예제 2: 배열 인덱스 초과

public class ArrayExample {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3};

        try {
            System.out.println(arr[5]); // 존재하지 않는 인덱스
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("배열 인덱스를 잘못 사용했습니다.");
        }
    }
}

✅ 예외 처리의 흐름 (try → catch → finally)

📌 finally 블록

  • 예외 발생 여부와 관계없이 항상 실행되는 블록

  • 보통 자원 정리(파일 닫기, DB 연결 종료 등) 에 사용

try {
    System.out.println("try 블록 실행");
} catch (Exception e) {
    System.out.println("예외 발생!");
} finally {
    System.out.println("무조건 실행되는 finally 블록");
}

✅ 다중 catch (여러 예외를 처리하고 싶을 때)

try {
    String str = null;
    System.out.println(str.length()); // NullPointerException
} catch (ArithmeticException e) {
    System.out.println("수학 오류");
} catch (NullPointerException e) {
    System.out.println("Null 객체 접근 오류");
} catch (Exception e) {
    System.out.println("기타 예외 발생");
}
  • 가장 구체적인 예외부터 먼저 catch!

  • Exception은 모든 예외의 부모 클래스이기 때문에 맨 마지막에 위치해야 합니다.

✅ 예외 처리하지 않으면 어떻게 되나요?

public class NoTryCatch {
    public static void main(String[] args) {
        int x = 5 / 0;  // 예외 발생
        System.out.println("이 코드는 실행되지 않음");
    }
}

예외가 발생하면 프로그램은 즉시 종료, 그 이후 코드는 실행되지 않음.

✅ 예외를 강제로 발생시키기 (throw)

public class CustomThrow {
    public static void main(String[] args) {
        try {
            throw new IllegalArgumentException("잘못된 입력입니다.");
        } catch (IllegalArgumentException e) {
            System.out.println("예외 메시지: " + e.getMessage());
        }
    }
}

🎯 한 줄 요약

try-catch는 예외가 발생해도 프로그램이 죽지 않도록 보호하고,
예외 상황에 맞는 적절한 처리를 가능하게 해주는 구문입니다.

profile
처음이라서 그래 가본적 없던 길에

0개의 댓글