例外処理
●例外処理の構文
try{
例外の発生を調べる文;
}catch(例外のクラス 変数名)
例外が起きたときに処理する文;
}
●例外処理とは
例外処理とは、例外に対して適切な処理できるコードを作ることで
エラーに強いプログラムを作成することを言います。
tryブロック内で例外が起こると処理を中断し、
例外がcatchブロックの条件を一致していれば、
catch内の処理を行います。
catchブロックが終わったらtry〜catchブロックのあとから処理が続きます。
●サンプル
class Sample1 {
public static void main(String args[]){
int a[]=new int[10];
try{
for(int i=0;i<11;i++){
a[i]=100;
System.out.println(Integer.toString(a[i]));
}
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsExceptionが発生しました。");
}
}
}
●実行結果
100
100
100
100
100
100
100
100
100
100
ArrayIndexOutOfBoundsExceptionが発生しました。