상세 컨텐츠

본문 제목

언체크-런타임 예외

JAVA

by 성찬우 2022. 10. 3. 23:50

본문

Exception Architecture

 

  • Object 결국 예외도 객체이다. 
  • Throwable 최상위 계층에 있는 예외이다. Exception  Error 로 나뉜다. 
  • Error 시스템 예외이다. 절대 이 예외를 잡아 처리하려고 해서는 안된다. Throwable 같은 곳에서도 catch 로 잡으면 자식까지도 잡을수 있기 때문에 Error도 같이 잡혀들어올 가능성이 있으므로 조심해야한다. 
  • Exception 은 체크 예외이다. 우리가 로직에서 핸들링이 가능한 실질적인 최상위 예외이다. 체크 예외는 컴파일러가 체크한다.
  • RuntimeException 언체크 예외인데 하위 계층까지 모두 "런타임 예외"라고도 불리운다. 

 

전글과 동일한 아키텍쳐이다. 

 

Unchecked Exception, Runtime Exception

런타임 언체크 예외는 컴파일러가 예외를 체크하지 않았다는 것이다. 

체크 예외와 기본 틀은 비슷하지만 

 

  • 체크 예외는 예외를 잡아서 처리하지 않으면 항상 throws를 통해 던져줘야하는데
  • 언체크 예외는 예외를 잡아서 처리하지 않아도 throws를 생략 가능하다.

체크 예외에서는 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

 

 

 

 

 

 

 

 

 

 

 

 

 

'JAVA' 카테고리의 다른 글

Map  (0) 2022.10.18
[체크,언체크] 예외의 활용  (0) 2022.10.04
자바의 체크 예외 'catch' or 'throw'  (0) 2022.10.01
java 8 : stream  (0) 2022.09.14

관련글 더보기

댓글 영역