public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}
//Sample19_26.java class Sample19_26{ /* charAtメソッドが例外をスローすると 変数 ch にアスタリスクを代入する例 */ public static void main(String[] args){ String str = "ヒザカックン"; // 文字数 6 int index = 6; char ch; final char ch0 = '*'; //代替え文字 try{ ch = str.charAt(index); }catch( StringIndexOutOfBoundsException e){ e.printStackTrace(); ch = ch0; } System.out.println("str[" + index + "] = [" + ch + "]"); } }
>cd ws ws>javac -encoding UTF-8 Sample19_26.java ws>java Sample19_26 java.lang.StringIndexOutOfBoundsException: String index out of range: 6 at java.lang.String.charAt(Unknown Source) at Sample19_26.main(Sample19_26.java:9) str[6] = [*]
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];//ココで ArrayIndexOutOfBoundsException
}
//Sample19_22.java class Sample19_22{ public static void main(String[] args){ imitationString imiStr = new imitationString("ヒザカックン"); try{ System.out.println(imiStr.imitationCharAt(6)); System.out.println("end of try."); }catch(ArrayIndexOutOfBoundsException e){ System.out.println(e);//例外の表示 } System.out.println("complete"); } } class imitationString{ /* * ニセStringクラス */ final char[] value; /*コンストラクタ*/ imitationString(String str){ value = str.toCharArray(); } /*ニセCharAtメソッド*/ public char imitationCharAt(int index) { return value[index];//ココで ArrayIndexOutOfBoundsException } }
ws>javac -encoding UTF-8 Sample19_22.java ws>java Sample19_22 java.lang.ArrayIndexOutOfBoundsException: 6 complete