커스텀 Exception 클래스 만들기

커스텀 Exception 클래스를 생성하려고 Exception을 상속받아서 작성했었다.
구글링중 RuntimeException을 상속받아서 작성한 예제도 있었는데 차이점을 알게되었다.
나는 극한의 초보라서 기본적인 내용도 큰 깨우침이었다.
기본적인 내용이기 때문에 예제 코드와 짧은 주석만으로 충분히 파악하실수 있을것이당.

/**
 *  Exception을 상속받은 경우 throws를 선언하거나 try~catch로 잡아줘야 컴파일 에러거 발생하지 않는다.
 */
class CheckedApiException extends Exception {
  public CheckedApiException() {
  }

  public CheckedApiException(String message) {
    super(message);
  }
}

/**
 *  RuntimeException을 상속받은 경우 throws Exception을 강제하지 않으며 try ~ catch도 강제하지 않는다.
 */
class RunTimeApiException extends RuntimeException {
  public RunTimeApiException() {
  }

  public RunTimeApiException(String message) {
    super(message);
  }
}

class CheckedExceptionTest {
  public static void main(String[] args) throws CheckedApiException {
    throw new CheckedApiException("체크드");
//    try {
//      throw new CheckedApiException("체크드");
//    } catch (CheckedApiException e) {
//      e.printStackTrace();
//    }
//  }

  }
}
class RuntimeExceptionTest {
  public static void main(String[] args) {
    throw new RunTimeApiException("런타임");
  }
}

+ Recent posts