Java ランタイム例外

WBOY
リリース: 2024-08-30 16:14:06
オリジナル
228 人が閲覧しました

例外は、Java でコードを実行中にエラーが発生した場合にスローされるものです。 Java の RuntimeException は、Java プログラミング言語のすべての例外の親クラスと呼ばれるもので、プログラムまたはアプリケーションの実行中に発生するとクラッシュまたは故障します。ただし、他の例外と比較すると、これらは異なり、他の例外のようにコードで指定することで捕捉することはできません。

Java での RuntimeException の仕組み

Object -> の順でExceptionの親クラスに属します。投げ可能 ->例外 -> 実行時例外。したがって、これは、JVM (Java 仮想マシン) の通常の操作の実行中にスローされるすべての例外のスーパークラスとして呼び出すことができます。この RuntimeException とそのサブクラスは、「未チェック例外」と呼ばれる例外のクラスに分類されます。これらはコンストラクターまたはメソッドの句で指定できませんし、その必要もありません。

無料ソフトウェア開発コースを始めましょう

Web 開発、プログラミング言語、ソフトウェア テスト、その他

Java の RuntimeException のコンストラクター

以下は RuntimeException のコンストラクターです:

1. RuntimeException (): これにより、詳細メッセージが null である新しいランタイム例外がスローされます。

構文:

public RuntimeException()
ログイン後にコピー

ここでの原因は初期化されず、クラス Throwable.initCause (java.lang.Throwable) を呼び出すことで初期化できます。

2. RuntimeException (String msg): これも新しいランタイム例外をスローしますが、Java コードで提供した定義済みの詳細メッセージが含まれます。

構文:

public RuntimeException (String msg)
ログイン後にコピー

上記の関数と同様に、デフォルトでは原因は初期化されませんが、Throwable.initCause (java.lang.Throwable) を呼び出すことで同様に初期化できます。ここでの msg は詳細メッセージであり、後で Throwable.getMessage () メソッドで取得できるように保存されます。

3. RuntimeException (String msg, Throwable Cause): これは、定義されたエラー メッセージとその原因を含む新しいランタイム例外をスローします。

構文:

public RuntimeException (String message, Throwable cause)
ログイン後にコピー

ここでのメッセージは自動的に含まれないため、明示的に指定する必要があることに注意してください。ここでは、原因が Throwable.getCause () 関数から取得されます。ここでは、原因が存在しないか不明であることを表す null 値が許可されています。

4. RuntimeException (String msg, Throwable Cause, booleanenableSupp, booleanwritableStack): これにより、詳細なエラー メッセージ、その特定の原因、抑制が有効か無効かを表すenableSupp、およびその抑制が有効である writableStack を含む新しいランタイム例外が生成されます。スタック トレースが有効か無効か。

構文:

protected RuntimeException (String message,
Throwable cause,
booleanenableSuppression,
booleanwritableStackTrace)
ログイン後にコピー

これにより、定義された原因と指定された詳細メッセージ、その原因、抑制が有効か無効か、書き込み可能なスタック トレースが有効かどうかを含む新しい実行時例外が生成されます。ここでのメッセージは、表示している特定のメッセージ、メッセージが存在するかどうかを示す原因、enableSuppression は抑制が許可されているかどうかを示し、writableStackTrace はスタック トレースが書き込み可能であるかどうかを指定します。

5. RuntimeException (スロー可能な原因): これは、指定された原因と条件の指定された詳細なエラー メッセージ (cause==null ? null : Cause.toString ()) を持つ新しいランタイム例外をスローします。これには、基本的にクラスとその特定のクラスがあります。原因メッセージ。

構文:

public RuntimeException (Throwable cause)
ログイン後にコピー

原因は、後で Throwable.getCause() メソッドによって取得できるように保持され、null 値が許可される場合、その原因が不明であることを示します。

Java で RuntimeException を回避するには?

このような例外を回避するために行う方法は、例外処理と呼ばれます。これは、開発者がコーディング中に心に留めておくべき最も基本的なことの 1 つです。例外が発生し、例外を処理できない場合、コード全体が役に立たなくなります。

Java でチェック例外を処理するには、throw および throw と呼ばれる特定の句を使用します。実行時例外は通常、入力に問題があるために発生し、ArrayIndexOutOfBoundsException、IllegalArgumentException、NumberFormatException、または NullPointerException などの例外を引き起こします。これらのエラーをコードに含めても、処理に変更はありませんが、ドキュメントの作成にグッド プラクティスとして使用できます。

以下のようにランタイム例外をカスタム定義できます:

public class AuthenticateUser extends RuntimeException {
public AuthenticateUser (String msg) {
super (msg);
}
}
ログイン後にコピー

以下は 4 つの主要な種類のランタイム例外の例です。

例 #1 – ArrayIndexOutOfBoundsException

これは、無効または使用できない配列のインデックス値をリクエストしたときに発生します。

Code:

public class Main
{
public static void main (String[] args)
{
// Random array of numbers
intip[] = {16, 17, 18, 19, 20};
for (inti=0; i<=ip.length; i++)
System.out.println (ip[i]);
}
}
ログイン後にコピー

Output:

Java ランタイム例外

As seen in this example, in the input array has its index value from 0 to 4. But in this for loop, the length of the array retrieved will be 5, and when that is tried to access in the array, it will throw the ArrayIndexOutOfBoundsException during RunTime of the code.

Example #2 – IllegalArgumentException

The cause of this exception is when the argument format provided is invalid.

Code:

public class Main {
inti;
public void getMark (int score) {
if (score < 0 || score > 100)
throw new IllegalArgumentException (Integer.toString (score));
else
i = score;
}
public static void main (String[] args) {
Main t = new Main ();
t.getMark (30);
System.out.println (t.i);
Main t1 = new Main ();
t1.getMark (120);
System.out.println (t1.i);
}
}
ログイン後にコピー

Output:

Java ランタイム例外

Here we know that the maximum value of a percentage value is 100. So when we pass the value as 101, we get the Illegal argument exception during run time.

Example #3 – NumberFormatException

This exception is usually thrown when a string is to be converted to a numeric value like either float or integer value, but the form of the string given as input is either illegal or inappropriate.

Code:

public class Main {
// giving input string as null
public static void main (String[] args) {
inti = Integer.parseInt (null);
}
}
ログイン後にコピー

Output:

Java ランタイム例外

In this example, we are giving the input string to be parsed into an integer as null. Hence the number format exception is thrown.

Example #4 – NullPointerException

This exception occurs when a reference object that the variable is referring to is null.

Code:

public class Main {
public static void main (String[] args) {
Object reference = null;
reference.toString ();
}
}
ログイン後にコピー

Output:

Java ランタイム例外

In this example, we are creating an object called reference having a null value. The same object is being called for an operation, and hence this error is thrown.

Conclusion: Runtime exceptions are thrown at runtime and hence difficult to be detected during compile time. They are difficult to handle, and the throws clause can only be used to define them but not catch them.

Recommended Article

This is a guide to Java RuntimeException. Here we discuss the Introduction and how to Avoid RuntimeException in Java, and it’s Working along with its examples. You can also go through our other suggested articles to learn more –

  1. Introduction to Heap Sort in Java
  2. Overriding in Java (Examples)
  3. Iterators in C# With Advantages and Disadvantages
  4. Top 10 Java Collection Interview Questions

以上がJava ランタイム例外の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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