Java

【Java】ArrayIndexOutOfBoundsとIndexOutOfBoundsの違い

こんにちは、ともです。

JavaSilverの勉強をしていまして

  • IndexOutOfBoundsException
  • StringOutOfBoundsException
  • ArrayIndexOutOfBoundsException

などの問題が出てきました。それらについて理解をまとめておきます。

継承関係

java.langパッケージの中をみてみました。

StringOutOfBoundsExceptionとArrayIndexOutOfBoundsExceptionがIndexOutOfBoundsExceptionを継承していることがわかります。

各例外の説明

IndexOutOfBoundsException 配列の範囲外を参照したことによりthrowされる例外
StringOutOfBoundsException 文字列の範囲外を参照したことによりthrowされる非検査例外
ArrayIndexOutOfBoundsException 配列の範囲外を参照したことによりthrowされる非検査例外

IndexOutOfBoundsExceptionを継承しているので、StringOutOfBoundsExceptionとArrayIndexOutOfBoundsExceptionはより詳細な例外という感じでしょうか。

次にコードを記述します。

// ①IndexOutOfBoundsException
ArrayList<String> al = new ArrayList<String>();
al.get(0);

// ②ArrayIndexOutOfBoundsException
int[] a = {1};
System.out.println(a);

// ③StringOutOfBoundsException
String str = "str";
System.out.println(str.charAt(5));

②のように配列を作成した場合はArrayIndexOutOfBoundsExceptionが発生しました。

③のようにjava.lang.Stringで文字列を作成し範囲外を参照した場合はStringOutOfBoundsExceptionが発生しました。

①のようにjava.util.ArrayListで配列を作成し、範囲外を参照した場合はIndexOutOfBoundsExceptionが発生しました。

apiからどのメソッドでどの例外をthrowするか調べれば良い話ではあります。

テストの為に次のように覚えておこうと思います。

  • インポートしないで使えるStringや配列はよりサブクラスの例外をthrow
  • java.util.ArrayListのようにインポートする必要のあるものは親クラスの例外をthrow