SPRING BOOT 예외 처리
Source: Dev.to
1. 예외란?
Exception = 프로그램의 정상 흐름을 방해하는 원치 않는 상황.
예외 처리의 목표
- 프로그램 충돌 방지
- 오류 제어
- 적절한 메시지 제공
2. Java 예외 계층 구조
Throwable
├── Error
└── Exception
├── RuntimeException (Unchecked)
└── Other Exceptions (Checked)
3. 예외 유형 (Java 수준)
(A) 체크 예외
- 컴파일 시점에 체크됨
- 핸들링이 필요함 (
try‑catch또는throws) Exception을 상속 (하지만RuntimeException은 아님)
Examples: IOException, SQLException, ClassNotFoundException, FileNotFoundException, InterruptedException
(B) 언체크 예외
- 런타임에 발생
- 핸들링은 선택 사항
RuntimeException을 상속
Examples: NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException, NumberFormatException, IllegalArgumentException
(C) 오류
- JVM/시스템 수준 문제
- 보통 처리하지 않으며, 사용자 정의
Error를 만드는 것은 권장되지 않음
Examples: OutOfMemoryError, StackOverflowError
4. Checked vs Unchecked 규칙
extends Exception → Checked Exception
extends RuntimeException → Unchecked Exception
extends Error → Error (avoid)
5. 다른 예외 확장
기술적으로는 가능하지만, 최선의 실천은 다음만 확장하는 것입니다:
- 체크 예외용
Exception - 언체크 예외용
RuntimeException
NullPointerException, IOException, SQLException 등과 같은 특정 예외를 확장하는 것은 피하십시오.
6. try‑catch vs throws
try‑catch
예외가 발생한 지점에서 처리합니다.
try {
FileReader fr = new FileReader("a.txt");
} catch (IOException e) {
System.out.println("File error");
}
throws
호출자에게 책임을 위임합니다.
public void readFile() throws IOException {
FileReader fr = new FileReader("a.txt");
}
Rule: 체크된 예외는 반드시 잡히거나 throws로 선언되어야 합니다.
7. throw vs throws
throw– 예외를 수동으로 발생시킵니다.
throw new IOException("File not found");
throws– 메서드가 예외를 발생시킬 수 있음을 선언합니다.
public void read() throws IOException { }
8. 일반적인 예외 의미
ClassNotFoundException– 런타임에 클래스를 찾을 수 없음.FileNotFoundException– 파일이 없거나 경로가 잘못됨.IOException– 파일, 네트워크, 스트림 관련 문제.SQLException– SQL 데이터베이스 오류 (MySQL, PostgreSQL, Oracle). MongoDB에서는 사용되지 않음.- MongoDB 대응 예외:
MongoException,DuplicateKeyException. InterruptedException–sleep,wait,join중에 스레드가 중단됨.
9. Custom Exceptions
Checked Custom Exception
class MyCheckedException extends Exception {
}
Unchecked Custom Exception
class MyUncheckedException extends RuntimeException {
}
10. Java vs Spring Boot 예외 처리
Java 수준
try‑catchthrows- 메서드 수준 처리
Spring Boot 수준
- Controller/API 수준 처리
- 클라이언트에 JSON 응답 반환
- 어노테이션:
@ExceptionHandler,@ControllerAdvice/@RestControllerAdvice
11. Spring Boot 예외 처리 예제
사용자 정의 예외
class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String msg) {
super(msg);
}
}
전역 핸들러
@RestControllerAdvice
class GlobalExceptionHandler {
@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity handle(UserNotFoundException e) {
return ResponseEntity.status(404).body(e.getMessage());
}
@ExceptionHandler(Exception.class)
public ResponseEntity handleAll(Exception e) {
return ResponseEntity.status(500).body("Server Error");
}
}
컨트롤러
@GetMapping("/user/{id}")
public User getUser(@PathVariable int id) {
return repo.findById(id)
.orElseThrow(() -> new UserNotFoundException("User not found"));
}
12. 핵심 인터뷰 포인트
- Checked exception: 컴파일 시점, 반드시 처리해야 함.
- Unchecked exception: 런타임 시점, 처리 선택적.
SQLException은 관계형 데이터베이스에만 적용되며, MongoDB에는 적용되지 않음.- 사용자 정의 예외: 체크 예외는
Exception을, 언체크 예외는RuntimeException을 상속. - Spring Boot는 전역적으로 API 오류를 처리하기 위해
@ControllerAdvice(or@RestControllerAdvice)를 사용함.
13. 요약
| 유형 | 확장 | 처리 방식 |
|---|---|---|
| Checked | Exception | try‑catch 또는 throws |
| Unchecked | RuntimeException | 선택적 |
| Error | Error (피함) | 처리하지 않음 |