Exception Architecture
전글과 동일한 아키텍쳐이다.
Unchecked Exception, Runtime Exception
런타임 언체크 예외는 컴파일러가 예외를 체크하지 않았다는 것이다.
체크 예외와 기본 틀은 비슷하지만
체크 예외에서는 Exception 을 상속받아서 체크 예외를 발생시키고 이를 잡거나 던졌는데
언체크 예외에서는 RuntimeException 을 상속받아서 예외를 발생시킨다.
체크 예외에서는 throw Exception 을 선언해주어야 컴파일 오류가 발생하지 않았지만
언체크 예외에서는 다음과 같이 컴파일 오류가 발생하지 않는다.
이것이 아까 말했던 예외를 잡아서 처리하지 않아도 throws를 생략할 수 있다는 것이다.
즉, 런타임 예외의 경우 선언을 해주지 않아도 계속해서 던진다는 것이다.
@Slf4j
public class UncheckException {
static class RuntimeExceptionExtends extends RuntimeException {
public RuntimeExceptionExtends(String message) {
super(message);
}
}
static class ThrowRuntimeExeption {
public void makeException() {
throw new RuntimeExceptionExtends("throw Exception");
}
}
static class CatchRuntimeExeption {
ThrowRuntimeExeption throwRuntimeExeption = new ThrowRuntimeExeption();
public void catchException() {
try {
throwRuntimeExeption.makeException();
} catch (RuntimeExceptionExtends e) {
log.error("error message = {}", e.getMessage(), e);
}
}
public void throwException(){
throwRuntimeExeption.makeException();
}
}
}
최종적으로는CatchRuntimeExeption.class 에서 try-catch 문으로 잡아 처리하거나 던지는 매서드를 생성했다.
테스트 코드로 한번 확인해보자면
@Test
void catchUnchecked() {
CatchRuntimeExeption catchException = new CatchRuntimeExeption();
catchException.catchException();
}
@Test
void ThrowUnchecked() {
CatchRuntimeExeption catchException = new CatchRuntimeExeption();
Assertions.assertThatThrownBy(()-> catchException.throwException())
.isInstanceOf(RuntimeExceptionExtends.class);
}
체크 예외랑 동일하게 catch 처리가 됬을 경우 문제가 없지만
throwException 콜로 인해 또 던질경우 예외로 인해서 RuntimeExceptionExtend.class 로 받아주었다.
체크 예외와 언체크 예외가 그래서 뭐가 다른건가..
항목 | 체크 예외 | 언체크 예외 |
시점 | 컴파일 시점 | 런타임 시점 |
처리 방법 | 반드시 선언하여 처리한다. | 선언이 필요 없다. 해선 안된다는 아니다. |
트랜잭션 | 예외 발생시 롤백하지 않는다. | 예외 발생시 롤백 해야한다. |
예시 | IOException, ClassNotFoundException..etc | NullPointerException, ClassCastException...etc |
Map (0) | 2022.10.18 |
---|---|
[체크,언체크] 예외의 활용 (0) | 2022.10.04 |
자바의 체크 예외 'catch' or 'throw' (0) | 2022.10.01 |
java 8 : stream (0) | 2022.09.14 |
댓글 영역