写一个数组越界,使用try、catch、finally捕捉。并在finally中判断是否有异常
数组越界就是数组在使用的长度超出了声明的长度。
public class Main {
public static void main(String[] args) {
//长度为2的数组
int num[] = {1,3};
//打印 num 数组中的第三个数(从0开始算0,1,2)
System.out.print(num[2]);
}
}
运行下然后看 IDE 报什么异常
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
使用try..catch语句进行捕捉
try {
int num[] = {1,3};
System.out.print(num[2]);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界");
}
最后用标志位进行判断
boolean isException = false;
try {
int num[] = {1,4,6};
System.out.print(num[2]);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界");
isException = true;
}finally {
if(isException){
System.out.println("有异常");
}else {
System.out.println("不存在异常");
}
}
我也是菜鸟,多尝试才能学会编程 ^_^