체크 예외 VS 언체크 예외
언체크 예외 전체 코드
package hello.jdbc.exception.basic;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
@Slf4j
public class UncheckedTest {
@Test
void unchecked_catch() {
Service service = new Service();
service.callCatch();
}
@Test
void unchecked_throw() {
Service service = new Service();
Assertions.assertThatThrownBy(() -> service.callThrow())
.isInstanceOf(MyUncheckedException.class);
}
/**
* RuntimeException 을 상속받은 예외는 언체크 예외가된다.
*/
static class MyUncheckedException extends RuntimeException {
public MyUncheckedException(String message) {
super(message);
}
}
/**
* UnChecked 예외는
* 예외를 잡거나, 던지지 않아도 된다.
* 예외를 잡지 않으면 자동으로 밖으로 던진다.
*/
static class Service {
Repository repository = new Repository();
/**
* 필요한 경우 예외를 잡아서 처리하면 된다.
*/
public void callCatch() {
try {
repository.call();
} catch (MyUncheckedException e) {
//예외 처리 로직
log.info("예외처리, message={}", e.getMessage(), e);
}
}
/**
* 예외를 잡지 않아도된다. 자연스럽게 상위로 넘어간다.
* 체크 예외와 다르게 throws 예외 선언을 하지 않아도 된다.
*/
public void callThrow() {
repository.call();
}
}
static class Repository {
public void call() {
throw new MyUncheckedException("ex");
}
}
}
언체크 예외를 잡아서 처리하는 코드
public void callCatch() {
try {
repository.call();
} catch (MyUncheckedException e) {
//예외 처리 로직
log.info("예외처리, message={}", e.getMessage(), e);
}
}
언체크 예외도 필요한 경우 이렇게 잡아서 처리할 수 있다.
언체크 예외를 밖으로 던지는 코드 - 생략
public void callThrow() {
repository.call();
}
언체크 예외의 장단점
언체크 예외는 예외를 잡아서 처리할 수 없을 때, 예외를 밖으로 던지는 throws 예외 를 생략할 수 있다. 이것 때문에 장점과 단점이 동시에 존재한다.