[例1] 配列の添字が範囲を越えても、回避措置をとらない場合< ExceptionTest1.java >[例2] 配列の添字が範囲を越えている例外(ArrayIndexOutOfBoundsException)をtry-catch する例
/** * 配列の添字が範囲を越えている */ public class ExceptionTest1 { /** 最初に呼び出されるメソッド */ public static void main( String[] args ) { int[] myarray = new int[3]; System.out.println("Let myarray[100] into the value 0 ..."); myarray[100] = 0; // 例外が発生 System.out.println("done...."); System.out.println("exit...."); } }
※実行結果
% javac ExceptionTest1.java % java ExceptionTest1 Let myarray[100] into the value 0 ... Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100 at ExceptionTest1.main(ExceptionTest1.java, Compiled Code)ということで、実行自体が異常停止してしまいます。
< ExceptionTest2.java >
/** * 配列の添字が範囲を越えている例外をtry-catchする */ public class ExceptionTest2 { /** 最初に呼び出されるメソッド */ public static void main( String[] args ) { int[] myarray = new int[3]; try { System.out.println("Let myarray[100] into the value 0 ..."); myarray[100] = 0; // 例外が発生 System.out.println("done...."); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("can not let it ...."); System.out.println("exception# is " + e + "."); } System.out.println("exit...."); } }
※実行結果
% javac ExceptionTest2.java % java ExceptionTest2 Let myarray[100] into the value 0 ... can not let it .... exception# is java.lang.ArrayIndexOutOfBoundsException: 100. exit....ということで、こちらは例外ハンドラによって実行が継続されたことが判ります。
2003年10月4日 14:53 更新