3 回答
![?](http://img1.sycdn.imooc.com/545861b80001d27c02200220-100-100.jpg)
TA贡献1851条经验 获得超3个赞
是的,令人困惑。
在Java中,非函数的所有程序控制路径都必须以结束,否则将引发异常。这就是简单而明确的规则。voidreturn
但是,令人讨厌的是,Java允许您在一个块中添加一个多余 return的东西finally,它会覆盖以前遇到的任何东西return:
try {
return foo; // This is evaluated...
} finally {
return bar; // ...and so is this one, and the previous `return` is discarded
}
![?](http://img1.sycdn.imooc.com/533e4bd900011a1d02000200-100-100.jpg)
TA贡献1876条经验 获得超5个赞
如果我尝试了,那就赶上了,最后我不能在try块中放入return。
你绝对可以。您只需要确保方法中的每个控制路径都正确终止即可。我的意思是:方法中的每个执行路径都以return或结尾throw。
例如,以下工作:
int foo() throws Exception { … }
int bar() throws Exception {
try {
final int i = foo();
return i;
} catch (Exception e) {
System.out.println(e);
throw e;
} finally {
System.out.println("finally");
}
}
在这里,您有两种可能的执行路径:
final int i = foo()
任何一个
System.out.println("finally")
return i
或者
System.out.println(e)
System.out.println("finally")
throw e
如果没有抛出异常,则采用路径(1,2)foo
。如果引发异常,则采用路径(1,3)。请注意,在两种情况下,如何在离开该方法之前finally
执行该块。
![?](http://img1.sycdn.imooc.com/54585094000184e602200220-100-100.jpg)
TA贡献1854条经验 获得超8个赞
最后块将始终执行即使我们陷入异常catch块,甚至我们的try块按预期执行。
因此,何时finally块将在流程中执行...
如果我们在try / catch块中有return语句,那么在执行return语句之前,将执行finally块(就像关闭连接或I / O一样)
function returnType process() {
try {
// some other statements
// before returning someValue, finally block will be executed
return someValue;
} catch(Exception ex) {
// some error logger statements
// before returning someError, finally block will be executed
return someError;
} finally {
// some connection/IO closing statements
// if we have return inside the finally block
// then it will override the return statement of try/catch block
return overrideTryCatchValue;
}
}
但是,如果您在finally语句中包含return语句,则它将覆盖try或catch块中的return语句。
添加回答
举报