risc-v中文社区

 找回密码
 立即注册
查看: 834|回复: 0

[原创] java for risc-v系列知识讲座(14)--- 异常处理

[复制链接]

20

主题

23

帖子

96

积分

注册会员

Rank: 2

积分
96
发表于 2021-8-17 09:05:13 | 显示全部楼层 |阅读模式
本帖最后由 szy 于 2021-8-17 09:07 编辑

public static void main(String[] args)
{
        int arr[] = new int[5];
        try { //将可能会出异常的代码放在try块中
                arr[5] = 10;//这句超索引范围
                System.out.println(arr[5]);
        }
        catch (IllegalArgumentException ie) { //捕获异常,可以有多个catch
                System.out.println("IllegalArgumentException");
        }
        catch (ArrayIndexOutOfBoundsException ae) {
                System.out.println("ArrayIndexOutOfBoundsException");
        }
        finally {  //不管有没产生异常,最终都会执行finally
                System.out.println("finally");
        }
}
显示如下:
ArrayIndexOutOfBoundsException
finally
上面代码是java早期写法,现在的catch可以融合多个异常类:
try {
        arr[5] = 10;
        System.out.println(arr[5]);
}
catch (IllegalArgumentException | ArrayIndexOutOfBoundsException e) {
        System.out.println("IllegalArgumentException | ArrayIndexOutOfBoundsException");
}
finally {
        System.out.println("finally");
}

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则



Archiver|手机版|小黑屋|risc-v中文社区

GMT+8, 2024-5-5 00:46 , Processed in 0.013314 second(s), 17 queries .

risc-v中文社区论坛 官方网站

Copyright © 2018-2021, risc-v open source

快速回复 返回顶部 返回列表