异常注意事项-多异常的捕获处理和finally有return语句

异常注意事项-多异常的捕获处理

多个异常使用捕获又该如何处理呢?

  1.多个异常分别处理。

  2.多个异常一次捕获,多次处理。

  3.多个异常一次捕获一次处理。

复制代码
//1.多个异常分别处理。
        try{
              int[] arr = {1,2,3};
              System.out.println(arr[3]);//ArrayIndexOutOfBoundsException: 3
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println(e);
        }
        try{
            List<Integer> list = List.of(1,2,3);
            System.out.println(list.get(3)); // IndexOutOfBoundsException: Index 3 out-of-bounds for length 3
        }catch(ArrayIndexOutOfBoundsException e){
            System.out.println(e);
        }
复制代码

 

复制代码
//2.多个异常一次捕获,多次处理。如果catch中定义的异常变量存在字符类关系,
        //   那么子类异常变量必须写在上面否则会报错。
        try{
            int[] arr = {1,2,3};
            //System.out.println(arr[3]);//ArrayIndexOutOfBoundsException
            List<Integer> list = List.of(1,2,3);
            System.out.println(list.get(3)); // IndexOutOfBoundsException: Index 3 out-of-bounds for length 3
        }catch(ArrayIndexOutOfBoundsException e){
            System.out.println(e);
        }catch (IndexOutOfBoundsException e){
            System.out.println(e);
        }
复制代码

 

 

 

异常注意事项-finally有return语句

复制代码
 public static void main(String[]args) {
        int a = getA( );
        System.out.println(a);
    }
    //定义一个方法,返回变量a的值
    public static int getA(){
    int a = 10;
    try{
        return a;
    }catch (Exception e){
        System.out.println(e) ;
    }finally {
    //一定会执行的代码a = 100;
        return a;
        }
    }
复制代码
复制代码
package exception;

public class Demo06 {
    public static void main(String[] args) {
        System.out.println(func());
    }

    public static int func(){
        int a = 10;
        try{
            System.out.println("try中的代码块");
            return a += 10;
        }catch (Exception e){
            System.out.println("catch中的代码块");
        }finally {
            System.out.println("finally中的代码块");
            if(a > 10){
                System.out.println("a > 10,"+"a="+a);
            }
        }
        return a += 50;
    }
}
复制代码

 

posted @   漁夫  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示