javaStudy > Exception

例外の発生

public class ExceptionTest1 {
	public static void main(String[] args) {
		int [] myarray = new int[3];
		System.out.println("代入します");
		myarray[100] = 0;
		System.out.println("代入しました");
		System.out.println("終了します");
	}
 }
guinessLover-no-MacBook-Pro:Exception shinsuke$ java ExceptionTest1
代入します
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
	at ExceptionTest1.main(ExceptionTest1.java:5)

例外のキャッチ

public class ExceptionTest2 {
	public static void main(String[] args) {
		int [] myarray = new int[3];
		try {
			System.out.println("代入します");
			myarray[100] = 0;
			System.out.println("代入しました");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("代入できませんでした");
			System.out.println("例外は" + e + "です");
		} 
		System.out.println("終了します");
	}
}
guinessLover-no-MacBook-Pro:Exception shinsuke$ java ExceptionTest2
代入します
代入できませんでした
例外はjava.lang.ArrayIndexOutOfBoundsException: 100です
終了します
最終更新:2009年11月17日 21:19