java - 异常处理
巴扎黑
巴扎黑 2017-04-17 11:15:57
[Java讨论组]

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

巴扎黑
巴扎黑

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

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号