Rol*_*all 61 java return finally try-catch
通过阅读本论坛中已经提到的与上述主题相关的所有问题(参见标题),我完全理解finally总是被称为.(除了System.exit和无限循环).但是,我想知道是否return在catch块中调用了a,然后return从finally块调用了另一个.
例如:
public static void main(String[]args) {
int a = new TestClass().absorbeTheValue();
}
int absorbeTheValue() {
try {
int a = 10/0;
if (a > 0) return 4;
} catch(Exception e) {
return 45;
} finally {
return 34;
}
}
Run Code Online (Sandbox Code Playgroud)
所以这里输出(当调用方法时)在任何情况下都是34.这意味着终于总能运行.我认为虽然其他"回归"根本没有运行.在很多帖子中,我发现最后将内容写入catch子句返回已写入的内容.我的理解是,一旦catch子句中的返回值即将被评估,控制流就会传递给finally子句,而子句又有另一个返回,这次返回将被评估,而不会将控制权传递给catch子句.通过这种方式,return在运行时唯一被调用的是最终返回.你同意吗?
甲return在finally不传递回控制到程序但返回值,并结束方法.我们可以这样说吗?
T.J*_*der 99
如果return在try到达块,它把控制权交给finally块,函数最终返回正常(不丢).
如果发生异常,但代码return从catch块到达a ,则控制转移到finally块并且函数最终正常返回(而不是抛出).
在你的例子中,你有一个returnin finally,所以无论发生什么,函数都会返回34,因为finally有最后的(如果你愿意)单词.
虽然在你的例子中没有涉及,但即使你没有catch并且如果一个异常被抛出try并且未被捕获,这也是如此.通过return从finally块中执行a ,您可以完全抑制异常.考虑:
public class FinallyReturn {
public static final void main(String[] args) {
System.out.println(foo(args));
}
private static int foo(String[] args) {
try {
int n = Integer.parseInt(args[0]);
return n;
}
finally {
return 42;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你运行它而不提供任何参数:
$ java FinallyReturn
... foo抛出的代码ArrayIndexOutOfBoundsException.但是因为finally块执行了a return,所以异常会被抑制.
这就是为什么它是最好避免使用return在finally.
and*_*dre 71
以下是一些显示其工作原理的代码.
class Test
{
public static void main(String args[])
{
System.out.println(Test.test());
}
public static String test()
{
try {
System.out.println("try");
throw new Exception();
} catch(Exception e) {
System.out.println("catch");
return "return";
} finally {
System.out.println("finally");
return "return in finally";
}
}
}
Run Code Online (Sandbox Code Playgroud)
结果是:
try
catch
finally
return in finally
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
100302 次 |
| 最近记录: |