3 回答

TA貢獻1851條經(jīng)驗 獲得超3個贊
是的,令人困惑。
在Java中,非函數(shù)的所有程序控制路徑都必須以結(jié)束,否則將引發(fā)異常。這就是簡單而明確的規(guī)則。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
}

TA貢獻1876條經(jīng)驗 獲得超5個贊
如果我嘗試了,那就趕上了,最后我不能在try塊中放入return。
你絕對可以。您只需要確保方法中的每個控制路徑都正確終止即可。我的意思是:方法中的每個執(zhí)行路徑都以return或結(jié)尾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");
}
}
在這里,您有兩種可能的執(zhí)行路徑:
final int i = foo()
任何一個
System.out.println("finally")
return i
或者
System.out.println(e)
System.out.println("finally")
throw e
如果沒有拋出異常,則采用路徑(1,2)foo
。如果引發(fā)異常,則采用路徑(1,3)。請注意,在兩種情況下,如何在離開該方法之前finally
執(zhí)行該塊。

TA貢獻1854條經(jīng)驗 獲得超8個贊
最后塊將始終執(zhí)行即使我們陷入異常catch塊,甚至我們的try塊按預(yù)期執(zhí)行。
因此,何時finally塊將在流程中執(zhí)行...
如果我們在try / catch塊中有return語句,那么在執(zhí)行return語句之前,將執(zhí)行finally塊(就像關(guān)閉連接或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語句。
添加回答
舉報