広告

Java : IndexOutOfBoundsException - API使用例

IndexOutOfBoundsException (Java SE 18 & JDK 18) の使用例まとめです。
だいたいのメソッドを網羅済みです。
API仕様のおともにどうぞ。


概要

ある種のインデックス(配列、文字列、ベクトルなど)が範囲外であることを示すためにスローされます。

クラス構成

IndexOutOfBoundsException は、インデックスで配列やリストなどの要素にアクセスするさい、そのインデックスが範囲外のときに発生する非チェック例外です。

配列の場合は、IndexOutOfBoundsException のサブクラスである ArrayIndexOutOfBoundsException が発生します。

final String[] array = {"aaa", "bbb", "ccc"};

System.out.println(array[0]); // aaa
System.out.println(array[1]); // bbb
System.out.println(array[2]); // ccc

// java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3
final var value1 = array[-1];

// java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
final var value2 = array[3];

基本的には、IndexOutOfBoundsException が発生したらそれはプログラムに問題があるときです。
IndexOutOfBoundsException が発生しないようにプログラムを修正しましょう。
( try ~ catch で IndexOutOfBoundsException を握りつぶすことはおすすめしません)

関連記事:例外 vs. 戻り値でエラーチェック


コンストラクタ

IndexOutOfBoundsException ()

詳細メッセージなしでIndexOutOfBoundsExceptionを構築します。

final var e = new IndexOutOfBoundsException();
System.out.println(e); // java.lang.IndexOutOfBoundsException

IndexOutOfBoundsException (int index)

不正なインデックスを示す引数を指定して、新しいIndexOutOfBoundsExceptionクラスを構築します。

final var e = new IndexOutOfBoundsException(123);
System.out.println(e); // java.lang.IndexOutOfBoundsException: Index out of range: 123

IndexOutOfBoundsException (long index)

不正なインデックスを示す引数を指定して、新しいIndexOutOfBoundsExceptionクラスを構築します。

final var e = new IndexOutOfBoundsException(10000000000L);
System.out.println(e); // java.lang.IndexOutOfBoundsException: Index out of range: 10000000000

IndexOutOfBoundsException (String s)

指定された詳細メッセージを持つIndexOutOfBoundsExceptionを構築します。

final var e = new IndexOutOfBoundsException("abcd");
System.out.println(e); // java.lang.IndexOutOfBoundsException: abcd

Throwableで宣言されたメソッド

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Java API 使用例 : Throwable」をご参照ください。


関連記事

ページの先頭へ