Exception(예외)은 프로그램 실행 중 발생하는 비정상적인 상황을 처리하기 위한 구조입니다.
예외는 예상 가능한 오류(예: 파일이 없거나, 잘못된 사용자 입력)로 인해 프로그램이 중단되지 않도록 도와줍니다.
자바에서는 예외 처리를 위해 try-catch와 같은 문법을 제공합니다.
Checked Exception
IOException, SQLException try-catch 또는 throws 키워드를 사용해야 합니다. Unchecked Exception
NullPointerException, ArrayIndexOutOfBoundsException Error
OutOfMemoryError, StackOverflowError try {
// 예외가 발생할 수 있는 코드
} catch (Exception e) {
// 예외 처리
} finally {
// 항상 실행되는 코드 (옵션)
}
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.");
}
}
}
필요에 따라 사용자 정의 예외를 만들 수 있습니다.
// 사용자 정의 예외 클래스
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.");
}
}
}
Spring에서는 예외를 관리하기 위해 아래와 같은 방법을 제공합니다.
예외 처리 메서드 사용 (@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());
}
}
Controller 레벨의 예외 처리
특정 컨트롤러에만 적용 가능한 예외 처리를 정의할 수 있습니다.
Global Exception 처리
@RestControllerAdvice 또는 HandlerExceptionResolver를 사용해 애플리케이션 전역의 예외를 처리합니다. try-catch를 단순히 붙이는 것으로 끝났지만, 점점 예외 처리의 중요성을 느끼며 특정 상황에 맞는 사용자 정의 예외를 만들거나 전역 예외 처리 방식을 고민하게 되었습니다.