Java基础——抛出异常时finally的作用

1.这是一道笔试题,分析以下程序的输出结果

package src;
class Test {
    public static void main(String[] args) {
        System.out.println(test(null) + "," + test("0") + "," + test(""));
    }

    public static int test(String str) {
        try {
            return str.charAt(0) - '0';
        } catch (NullPointerException e1) {
            System.out.println("this is in 1");
            return 1;
        } catch (StringIndexOutOfBoundsException e2) {
            System.out.println("this is in 2");
            return 2;
        } catch (Exception e3) {
             System.out.println("this is in 3");
            return 3;

        } finally {
            return 4;
        } 

    }
}

结果是:
this is in 1
this is in 2
4,4,4


这个问题很有疑惑性

  1. return定义及用法:他返回一个返回值,并且终止函数进程
  2. finally定义及用法:用在抛出异常程序中,只要是捕获到了异常,finally代码块无条件必须执行。

由此,分析此题

  • 当程序执行时,代码test(null)会抛出(NullPointerException e1),因此会输出this is in 1
  • 当程序执行完这个异常检测程序的时候,无条件执行finally代码块。因此会将第一个4返回。
  • 当程序执行到,test("0"),程序不抛出异常,但是因为try语句块已经执行,因此finally无条件,必须执行。

注意:只有与 finally 相对应的 try 语句块得到执行的情况下,finally 语句块才会执行。

比如:

package src;
class Test {
    public static void main(String[] args) {
        System.out.println(test("0") + "," + test("0") + "," + test(""));
    }

    public static int test(String str) {


        if(str.equals("0")){
        try {
            return str.charAt(0) - '0';
        } catch (NullPointerException e1) {
            System.out.println("this is in 1");
            return 1;
        } catch (StringIndexOutOfBoundsException e2) {
            System.out.println("this is in 2");
            return 2;
        } catch (Exception e3) {
             System.out.println("this is in 3");
            return 3;

        } finally {
            return 4;
        } 
        }
        else return 5;
    }
}

结果就是:
4,4,5

因为当最后test("")时,不满足IF条件,因此try语句没有执行,finally也就没有执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值