异常处理

新手上路,请多包涵

写一个数组越界,使用try、catch、finally捕捉。并在finally中判断是否有异常

阅读 3.7k
1 个回答

数组越界就是数组在使用的长度超出了声明的长度。

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("不存在异常");
        }
    }

我也是菜鸟,多尝试才能学会编程 ^_^

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏