티스토리 뷰

Java

[Java] CheckedException과 UncheckedException

Eastplanet 2025. 9. 23. 23:06

구조도

 

Error

발생해서는 안되는 비정상적인 상황

프로그램 코드 수준에서 해결할 수 없는 매우 심각한 시스템 오류를 의미하며, 개발자가 try-catch로 잡으려고 시도해서는 안되는 문제이다.

 

Exception

프로그램에 의해서 수습될 수 있는 오류

 

CheckedException

컴파일 시점에 예외에 대한 처리를 강제한다.

RuntimeException을 제외한 Exception과 Exception의 하위 클래스는 Checked Exception이다.

 

Unchecked Exception

예외에 대한 처리를 강제하지 않는다.

RuntimeException이 이에 속한다.

 

Rollback?

많은 곳에서 흔히 Checked Exception은 rollback을 하지 않고, Unchecked Exception은 rollback을 한다고 기술을 했고, 이 정보에 오류가 존재한다고 말하는 포스트를 많이 보았다.

Spring에서 처리해주는 부분을 java의 기능이라고 오해할 수 있기 때문이다.

 

스프링 공식문서에는 아래와 같이 기술되어 있다.

In its default configuration, the Spring Framework’s transaction infrastructure code marks a transaction for rollback only in the case of runtime, unchecked exceptions. That is, when the thrown exception is an instance or subclass of RuntimeException. (Error instances also, by default, result in a rollback).
https://docs.spring.io/spring-framework/reference/data-access/transaction/declarative/rolling-back.html

Unchecked인 Runtime Exception과 Error에 대해서 rollback을 해준다고 한다.

 

RuntimeException

@Transactional
public void test() {
    boardRepository.save(new Board());
    func();
}

public void func() {
    throw new RuntimeException("런타임 예외");
}

롤백이 잘 동작한다.

 

Error

@Transactional
public void test() {
    boardRepository.save(new Board());
    func();
}

public void func() {
    throw new Error("에러");
}

롤백이 잘 동작한다.

 

CheckException

@Transactional
public void test() throws Exception {
    boardRepository.save(new Board());
    func();
}

public void func() throws Exception {
    throw new Exception("Checked Exception");
}

CheckedException은 예외를 검사해야 한다. 하지만 내부에서 try-catch를 해버리면, runtime Exception 또한 커밋해주므로 예외를 던지는 방식으로 작성했다.

그 결과 예외가 발생했지만 커밋이 된 것을 볼 수 있다.

 

RuntimeException이 발생했지만, 개발자가 Exception으로 넘기면 어떻게 될까?

@Transactional
public void test() throws Exception {
    boardRepository.save(new Board());
    func();
}

public void func() throws Exception {
    throw new RuntimeException("runtime Exception");
}

이 경우에는 RuntimeException으로 처리되어 rollback이 동작한다.

 

CheckedException이 rollback을 수행하지 않는 이유

CheckedException은 코드에 의해 복구 가능성이 있는 상황이기 때문에 개발자의 판단에 따라 커밋할 수도 있기 때문이라고 한다. 또한 설정에 의해 CheckedException도 롤백을 수행하도록 할 수 있다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/01   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함