[英]Should last statement be `return` in and non void return types method?
應該return
last語句和非void返回類型方法嗎? 但這仍然有效。
public String test()
{
try
{
// Do my work
return "myValue";
}
finally
{
System.out.println("I'm in Finally");
}
}
我有點缺乏了解這項工作的知識。 有人能解釋我嗎?
這段代碼沒有問題,因為通過它的每條可能的路徑都不可避免地導致return
語句* 。 它不必是文本上的最后一個語句,只要它是邏輯上的最后一個語句(Java編譯器足夠聰明,可以弄清楚它是否如此,如果有代碼中的路徑沒有返回,則會給出錯誤)價值或拋出異常)。 事件是在命中return
后會執行代碼(即你的finally
塊)並沒有改變任何東西:就編譯器而言,你的函數在退出函數之前提供了一個返回值。
*實際上,函數代碼中只有一條路徑,它在return
語句處終止。
在Java中,確保所有可能的代碼路徑都返回值或拋出異常就足夠了。 例如,以下代碼有效:
public boolean test() {
if (3 < 5) {
return true;
} else {
throw new RuntimeException("Holy crap!");
}
}
在您的示例中,您的try
塊以返回結束,因此覆蓋了快樂路徑,並且不需要超出finally
代碼; 此外,在拋出的異常try
將傳播出來的方法,並且將沒有機會到達方法的結束,因此所有可能的路徑絕不會打到下的一節finally
阻止和不需要return語句。 (事實上,如果你在底部添加了一個return
語句,編譯器可能會給你一個關於無法訪問代碼的警告或錯誤!)
添加catch
子句時,事情會發生變化,因為現在代碼可能會超出try
/ catch
/ finally
塊:
public String test(){
try{
// Do my work
return "myValue";
}
catch (Exception ex) {
System.out.println("O noes something went wrong");
// swallow exception
}
finally {
System.out.println("I'm in Finally");
}
// Oh no! If an exception was caught, code can actually flow through here.
// Compiler will complain about a missing return statement until you add one.
// return "someOtherValue";
}
在這種情況下, try
並finally
始終執行。 所以, return
地方並不重要。
public String myfun(){
return "here";
}
or
public String myfun(){
try{
return "here";
}finally{
//will execute always
}
}
幾乎一樣。 什么時候,你看到程序的流程。 但是,如果有任何條件的話
public String myfun(){
if(x==1){
return "here";
}
else{
// something here
}
}
在這種情況下,它會引發錯誤 。 因為,任何一個塊都不會同時執行。 如同
public String fun(){
try{
return "here";
}
catch(Exception e){
//catch implementation without return
}
}
關鍵的JLS概念是正常和突然完成語句 ,結合try-finally的行為。
由於“myValue”的返回,try塊突然完成。 finally塊正常完成,因此整個try語句由於與try塊相同的原因突然完成,返回“myValue”。
實際上,方法中的最后一個語句try語句是返回String的語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.