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

来源:互联网 发布:python java android 编辑:程序博客网 时间:2024/06/05 00:09

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也就没有执行。

阅读全文
0 0
原创粉丝点击