8.1 异常
ArrayIndex.java
package exception;
import java.util.Scanner;
public class ArrayIndex {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = new int[10];
int idx;
Scanner in = new Scanner(System.in);
idx = in.nextInt();
try {
a[idx]=10;
System.out.println("hello");
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Caught");
}
}
}
运行结果
//输入
10
//控制台反馈
Caught
另一个程序
package exception;
import java.util.Scanner;
public class ArrayIndex {
public static void f() {
int[] a = new int[10];
a[10] = 10;
//由于上一行有异常,所以接下来的打印hello并不会输出
System.out.println("hello");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
f();
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Caught");
}
System.out.println("main ended");
}
}
运行直接结果
Caught
main ended
8.2 异常机制
8.3 流