try后面可以跟多个catch,但是只执行其中一个catch语句块。
捕捉到哪个异常就执行哪个,稍微特殊一点的情况是多个catch具有继承关系时,会执行子类异常语句块。这可能是因为异常书写的规定是子类在前,父类在后吧。
public class TryCatch {
public static void main(String[] args) {
int a[] = new int[10];
try {
a[10] = 1;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数据越界");
} catch (Exception e) {
System.out.println("运行异常");
} finally {
System.out.println("Finally");
}
}
}
输出为
数组越界
Finally