Java中异常处理之------throws

本文介绍了在Java编程中如何使用`throws`关键字将`ArrayIndexOutOfBoundsException`异常抛给上级方法,并在main方法中通过try-catch块捕获和处理异常,以及finally块的使用。
摘要由CSDN通过智能技术生成

当面临代码异常时可用throws关键字来向上一级(即被调用的函数)抛出异常,交给上一级进行处理

package Hello.lrx.deam;

public class Trows {
    static void show1() throws ArrayIndexOutOfBoundsException{
        int [] a={2,4,6,5};
        int x =a[8];
    }
    static void show2() throws ArrayIndexOutOfBoundsException{
       show1();
    }
    public static void main(String[] args) {
        show2();
      /*  try{
            show2();
        }catch(ArrayIndexOutOfBoundsException e){
            System.out.println("数组溢出异常");
            e.printStackTrace();
        }*/
    }
}

最终将异常抛给main方法

运行结果

最好在main方法使用try关键字处理异常

package Hello.lrx.deam;

public class Trows {
    static void show1() throws ArrayIndexOutOfBoundsException{
        int [] a={2,4,6,5};
        int x =a[8];
    }
    static void show2() throws ArrayIndexOutOfBoundsException{
       show1();
    }
    public static void main(String[] args) {
       // show2();
        try{
            show2();
        }catch(ArrayIndexOutOfBoundsException e){
            System.out.println("数组溢出异常");
            e.printStackTrace();
        }
        finally {
            System.out.println("程序结束" );
        }
    }
}

运行结果

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值