使用try-catch-finally返回类型

时间:2013-08-10 06:10:00

标签: java

我尝试了以下代码段:

private Integer getnumber() {
    Integer i = null;
    try {
        i = new Integer(5);
        return i;
    } catch(Exception e) {
        return 0;
    } finally {
        i = new Integer(7);
    }
}

此方法返回5而不是7。

  

为什么它返回5而不是7?

提前致谢。

5 个答案:

答案 0 :(得分:3)

这是因为finally的{​​{1}}块在try..catch..finally内的代码完成后运行(无论成功与否);对于您的代码,这是try..catch发生的时间。

由于此行为,return i的值已经放入方法的返回变量中,然后再为其分配新值7。以下方法可行:

i

答案 1 :(得分:0)

您已在finally中分配了值,在此之前您已返回try

最终总是执行代码,但您已经返回try

中的值

答案 2 :(得分:0)

这是因为return语句在finally执行之前执行,而i的值在执行return语句时为5。 要验证这一点,您可以执行此操作

private Integer getnumber(){
Integer i = null;
try{
   i = new Integer(5);
   return i;
}catch(Exception e){return 0;}
finally{
  i = new Integer(7);
  System.out.println(i);
}
}

打印7,因为finally块确实执行,但只是在return语句之后。

答案 3 :(得分:0)

finally中您要分配值,但在try

之前返回值

答案 4 :(得分:0)

返回值为5,因为在return块执行之前发生了finally