>  기사  >  Java  >  Java에서 사용자 정의 확인되지 않은 예외를 만드는 방법은 무엇입니까?

Java에서 사용자 정의 확인되지 않은 예외를 만드는 방법은 무엇입니까?

WBOY
WBOY앞으로
2023-09-11 16:37:021191검색

Java에서 사용자 정의 확인되지 않은 예외를 만드는 방법은 무엇입니까?

Java에서 RuntimeException을 확장하여 사용자 정의 uncheckedException을 만들 수 있습니다.

UncheckedExceptionError 클래스 또는 RuntimeException 클래스에서 상속됩니다. 많은 프로그래머들은 이러한 예외가 프로그램이 실행되는 동안 복구할 수 없는 오류 유형을 나타내기 때문에 프로그램에서 이러한 예외를 처리할 수 없다고 생각합니다. 확인되지 않은 예외가 발생하는 경우 일반적으로 코드 남용, null 전달 또는 기타 잘못된 매개변수로 인해 발생합니다.

Syntax
public class MyCustomException extends RuntimeException {
   public MyCustomException(String message) {
      super(message);
   }
}

확인되지 않은 예외 구현

맞춤형 확인되지 않은 예외 구현은 Java의 확인된 예외와 거의 유사합니다. 유일한 차이점은 확인되지 않은 예외는 Exception 대신 RuntimeException을 확장해야 한다는 것입니다.

public class CustomUncheckedException extends RuntimeException {
   /*
   * Required when we want to add a custom message when throwing the exception
   * as throw new CustomUncheckedException(" Custom Unchecked Exception ");
   */
   public CustomUncheckedException(String message) {
      // calling super invokes the constructors of all super classes
      // which helps to create the complete stacktrace.
      super(message);
   }
   /*
   * Required when we want to wrap the exception generated inside the catch block and rethrow it
   * as catch(ArrayIndexOutOfBoundsException e) {
      * throw new CustomUncheckedException(e);
   * }
   */
   public CustomUncheckedException(Throwable cause) {
      // call appropriate parent constructor
      super(cause);
   }
   /*
   * Required when we want both the above
   * as catch(ArrayIndexOutOfBoundsException e) {
      * throw new CustomUncheckedException(e, "File not found");
   * }
   */
   public CustomUncheckedException(String message, Throwable throwable) {
      // call appropriate parent constructor
      super(message, throwable);
   }
}

위 내용은 Java에서 사용자 정의 확인되지 않은 예외를 만드는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제