Javaでカスタムの未チェック例外を作成するにはどうすればよいですか?

WBOY
リリース: 2023-09-11 16:37:02
転載
1212 人が閲覧しました

Javaでカスタムの未チェック例外を作成するにはどうすればよいですか?

Java で RuntimeException を拡張することで、カスタム 未チェック Exception を作成できます。

UncheckedExceptionError クラスまたは RuntimeException クラスから継承します。多くのプログラマは、これらの例外はプログラムの実行中に回復できないタイプのエラーを表すため、プログラムでこれらの例外を処理することはできないと考えています。未チェック例外がスローされる場合、通常、 コード の悪用、 null またはその他の 不正な引数 が原因で発生します。

構文
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 中国語 Web サイトの他の関連記事を参照してください。

ソース:tutorialspoint.com
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!