24.12.05 TIL Exception

신성훈·2024년 12월 5일

TIL

목록 보기
93/162

Exception

1. Exception이란?

Exception(예외)은 프로그램 실행 중 발생하는 비정상적인 상황을 처리하기 위한 구조입니다.
예외는 예상 가능한 오류(예: 파일이 없거나, 잘못된 사용자 입력)로 인해 프로그램이 중단되지 않도록 도와줍니다.
자바에서는 예외 처리를 위해 try-catch와 같은 문법을 제공합니다.


2. Exception의 종류

  1. Checked Exception

    • 컴파일 시점에 반드시 처리해야 하는 예외
    • 예: IOException, SQLException
    • 예외 처리가 강제되므로 try-catch 또는 throws 키워드를 사용해야 합니다.
  2. Unchecked Exception

    • 런타임 시점에 발생하며, 컴파일러가 강제하지 않는 예외
    • 예: NullPointerException, ArrayIndexOutOfBoundsException
    • 개발자가 주의 깊게 작성해야 하는 오류.
  3. Error

    • 시스템 레벨에서 발생하는 심각한 문제로, 복구 불가능
    • 예: OutOfMemoryError, StackOverflowError

3. 자바에서 예외 처리

1) 기본 구조

try {
    // 예외가 발생할 수 있는 코드
} catch (Exception e) {
    // 예외 처리
} finally {
    // 항상 실행되는 코드 (옵션)
}

2) 예외 처리 예제

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;  // ArithmeticException 발생
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero: " + e.getMessage());
        } finally {
            System.out.println("Execution completed.");
        }
    }
}

4. 예외를 직접 정의하기

필요에 따라 사용자 정의 예외를 만들 수 있습니다.

// 사용자 정의 예외 클래스
class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

// 사용자 정의 예외 사용
public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            validateAge(15);
        } catch (CustomException e) {
            System.out.println("Custom Exception: " + e.getMessage());
        }
    }

    static void validateAge(int age) throws CustomException {
        if (age < 18) {
            throw new CustomException("Age must be 18 or older.");
        }
    }
}

5. Spring에서의 예외 처리

Spring에서는 예외를 관리하기 위해 아래와 같은 방법을 제공합니다.

  1. 예외 처리 메서드 사용 (@ExceptionHandler)

    @RestControllerAdvice
    public class GlobalExceptionHandler {
        @ExceptionHandler(Exception.class)
        public ResponseEntity<String> handleException(Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                                 .body("Error occurred: " + e.getMessage());
        }
    }
  2. Controller 레벨의 예외 처리
    특정 컨트롤러에만 적용 가능한 예외 처리를 정의할 수 있습니다.

  3. Global Exception 처리

    • @RestControllerAdvice 또는 HandlerExceptionResolver를 사용해 애플리케이션 전역의 예외를 처리합니다.

6. 마무리

  • 예외 처리는 코드의 안정성을 높이는 데 중요한 역할을 합니다.
  • 처음에는 try-catch를 단순히 붙이는 것으로 끝났지만, 점점 예외 처리의 중요성을 느끼며 특정 상황에 맞는 사용자 정의 예외를 만들거나 전역 예외 처리 방식을 고민하게 되었습니다.
  • Spring의 글로벌 예외 처리를 통해 코드의 일관성을 유지할 수 있다는 점을 배웠습니다.
profile
조급해하지 말고, 흐름을 만들고, 기록하면서 쌓아가자.

0개의 댓글