스프링이 제공하는 예외 추상화를 이해하기 위해서는 먼저 자바 기본 예외에 대한 이해가 필요하다.


예외를 처리하지 못하면 호출한 곳으로 예외를 계속 던지게 된다.
예외에 대해서는 2가지 기본 규칙을 기억하자!
→ 예외를 만약 처리하지 않고 계속 던지면?
package hello.jdbc.exception.basic;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Slf4j
public class CheckedTest {
@Test
void checked_catch(){
Service service = new Service();
service.callCatch();
}
@Test
void checked_throw() {
Service service = new Service();
assertThatThrownBy(() -> service.callThrow()).isInstanceOf(MyCheckedException.class);
}
/**
* Exception 상속 받은 예외는 체크 예외가 된다.
*/
static class MyCheckedException extends Exception {
public MyCheckedException(String message) {
super(message);
}
}
/**
* Checked 예외는
* 예외를 잡아서 처리하거나, 던지거나 둘 중 하나를 필수로 선택해야 한다.
*/
static class Service{
Repository repository = new Repository();
/**
* 예외를 잡아서 처리하는 코드
*/
public void callCatch() {
try {
repository.call();
} catch (MyCheckedException e) {
log.info("예외 처리, message = {}", e.getMessage(), e);
}
}
public void callThrow() throws MyCheckedException {
repository.call();
}
}
static class Repository {
public void call() throws MyCheckedException {
throw new MyCheckedException("ex");
}
}
}
→ 예외를 잡아서 처리하는 코드, 예외를 던지는 코드 비교.
package hello.jdbc.exception.basic;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Slf4j
public class UncheckedTest {
@Test
void unchecked_catch() {
Service service = new Service();
service.callCatch();
}
@Test
void unchecked_throw() {
Service service = new Service();
assertThatThrownBy(() -> service.callThrow()).isInstanceOf(MyUncheckedException.class);
}
/**
* RuntimeException 을 상속받은 예외는 언체크 예외가 된다.
*/
static class MyUncheckedException extends RuntimeException {
public MyUncheckedException(String message) {
super(message);
}
}
static class Service{
Repository repository = new Repository();
public void callCatch() {
try {
repository.call();
} catch (MyUncheckedException e) {
log.info("예외 처리, message={}", e.getMessage(), e);
}
}
public void callThrow() {
repository.call();
}
}
static class Repository {
public void call() {
throw new MyUncheckedException("EX");
}
}
}
그렇다면 언제 체크 예외를 사용하고, 언제 언체크 (런타임) 예외를 사용하면 좋을까?
기본 원칙은 다음 2가지를 기억하자
체크 예외의 문제점
체크 예외는 컴파일러가 예외 누락을 체크해주기 때문에 개발자가 실수로 예외를 놓치는 것을 막아준다.
그러나 왜 체크 예외를 기본으로 사용하는 것이 문제가 될까?
체크 예외 문제점

→ 이렇게 해결이 불가능한 공통 예외에는 오류 코드를 남기고, 개발자가 오류를 빨리 인지할 수 있도록 메일, 알림(문자, 슬랙 등) 을 통해 전달 받아야 한다.
체크 예외의 문제점 - 코드 예시
package hello.jdbc.exception.basic;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import java.net.ConnectException;
import java.sql.SQLException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class CheckedAppTest {
@Test
void checked() {
Controller controller = new Controller();
assertThatThrownBy(() -> controller.request()).isInstanceOf(Exception.class);
}
static class Controller{
Service service = new Service();
public void request() throws SQLException, ConnectException {
service.logic();
}
}
static class Service {
Repository repository = new Repository();
NetworkClient networkClient = new NetworkClient();
public void logic() throws SQLException, ConnectException {
repository.call();
networkClient.call();
}
}
static class NetworkClient {
public void call() throws ConnectException {
throw new ConnectException("연결 실패");
}
}
static class Repository {
public void call() throws SQLException {
throw new SQLException();
}
}
}
2가지 문제
복구 불가능한 예외
의존 관계에 대한 문제
복구 불가능한 예외
대부분의 예외는 복구가 불가능하다.
SQLException 을 예로 들면, 데이터베이스에 무언가 문제가 있어서 발생하는 예외이다. SQL 문법에 문제가 있을 수도 있고, 데이터베이스 자체에 뭔가 문제가 발생했을 수도 있다.
특히 대부분의 서비스나 컨트롤러는 이런 문제를 해결할 수는 없다. 따라서 이런 문제들은 일관성 있게 공통으로 처리해야 한다. 오류 코드를 남기고 개발자가 해당 오류를 빠르게 인지하는 것이 필요하다. 서블릿 필터, 스프링 인터셉터, 스프링의 ControllerAdvice 를 사용하면 이런 부분을 깔끔하게 공통으로 해결할 수 있다.
의존 관계에 대한 문제
체크 예외의 또 다른 심각한 문제는 예외에 대한 의존 관계 문제이다.
서비스나 컨트롤러에서 어쩔 수 없이 throws 로 던지는 예외를 선언해야 한다.
그러면 서비스나 컨트롤러에서 예외를 던지는 부분을 코드에 선언하는 것이 왜 문제가 될까?
왜? → 서비스, 컨트롤러에서 해당 예외에 의존하기 때문!
예시)
SQLExeption → java.sql.SQLExeption 이다. 이는 구체적인 JDBC 기술을 사용하는 것.
만약 향후 서비스를 JPA 를 사용하도록 수정 개발한다면?
서비스나 컨트롤러의 예외를 던지는 모든 코드를 SQLException → JPAException 으로 고쳐야 한다.
결과적으로 OCP, DI 를 통해 클라이언트 코드의 변경 없이 개상 구현체를 변경할 수 있다는 장점이 체크 예외 때문에 발목을 잡게 된다.

throws Exception
void method() throws SQLException, ConnectException {..} // 이것 대신
void method() throws Exception {...} //이걸 써보자.
→ 깔끔해진 것 같지만, SQLException, ConnectionException 뿐만 아닌 하위 타입 모든 체크 예외를 밖으로 다 던지는 꼴이다.
→ 꼭 필요한 경우가 아니라면, Exception 자체를 밖으로 던지는 것은 좋지 않은 방법이다.
이번에는 런타임 예외를 사용해보자.
package hello.jdbc.exception.basic;
import org.junit.jupiter.api.Test;
import java.net.ConnectException;
import java.sql.SQLException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class UncheckedAppTest {
static class RuntimeConnectionException extends RuntimeException {
public RuntimeConnectionException(String message) {
super(message);
}
}
static class RuntimeSQLException extends RuntimeException {
public RuntimeSQLException() {
}
public RuntimeSQLException(String message) {
super(message);
}
public RuntimeSQLException(String message, Throwable cause) {
super(message, cause);
}
public RuntimeSQLException(Throwable cause) {
super(cause);
}
public RuntimeSQLException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
@Test
void unchecked() {
Controller controller = new Controller();
assertThatThrownBy(() -> controller.request()).isInstanceOf(RuntimeException.class);
}
static class Controller{
Service service = new Service();
public void request() {
service.logic();
}
}
static class Service {
Repository repository = new Repository();
NetworkClient networkClient = new NetworkClient();
public void logic() {
repository.call();
networkClient.call();
}
}
static class NetworkClient {
public void call() {
throw new RuntimeConnectionException("연결 실패");
}
}
static class Repository {
public void call() {
try {
runSQL();
} catch (SQLException e) {
throw new RuntimeSQLException(e);
}
}
public void runSQL() throws SQLException {
throw new SQLException("ex");
}
}
}
예외 전환
예외를 전환할 때는 꼭!!!!!!!!!! 기존 예외를 포함해야 한다. 그렇지 않으면 스택 트레이스를 확인할 때 심각한 문제가 발생한다.
log.info("message={}", "message", ex) , 여기에서 마지막에 ex 를 전달하는 것을 확인할log.info("ex", ex) 지금 예에서는 파라미터가 없기 때문에, 예외만 파라미터에 전달하면 스택 트레이스를 로그에 출력할 수 있다.e.printStackTrace() 를 사용하면 된다.기존 예외를 포함 하는 경우
static class Repository {
public void call() {
try {
runSQL();
} catch (SQLException e) {
throw new RuntimeSQLException(e);
}
}
public void runSQL() throws SQLException {
throw new SQLException("ex");
}
}
기존 예외를 포함하지 않는 경우
public void call() {
try {
runSQL();
} catch (SQLException e) {
throw new RuntimeSQLException(); //기존 예외(e) 제외
}
}
→ 예외를 포함하지 않아서 기존에 발생한 java.sql.SQLException 과 스택 트레이스를 확인할 수 없다. 변환한 RuntimeSQLException 부터 예외를 확인할 수 있다. 만약 실제 DB에 연동했다면 DB에서 발생한 예외 (= root cause) 를 확인할 수 없는 심각한 문제가 발생한다.
🚨 예외를 전환할 때는 꼭!!!!!!! 기존 예외를 포함하자! 🚨