[英]Return statements in try/catch block Java
假設我有以下內容:
class NegativeException extends RuntimeException {
}
class ZeroException extends NegativeException {
}
class Driver {
static boolean Marathon(int a) {
try {
if (a < 0)
throw new NegativeException();
else if (a == 0)
throw new ZeroException();
else if (a >= 42)
return true;
else
return false;
} catch (ZeroException e) {
System.out.println("Use natural number");
} finally {
System.out.println("One last thing");
}
System.out.println("All done.");
return false;
}
public static void main(String[] args) {
/* One last thing */
/* true */
System.out.println(Marathon(100));
System.out.println(Marathon(0));
System.out.println(Marathon(-5));
}
}
我想要了解的是為什么當使用main方法的第一行時,“All done”行沒有被執行? Marathon(100)
似乎finally
語句執行,然后輸出return
語句。 我知道finally
塊將始終執行,無論發生什么。 但是,我似乎無法理解return語句如何影響try catch
塊的流程。 嘗試從try-cath-finally
塊返回時是否有一套適用的規則?
我想要了解的是為什么當使用main方法的第一行時,“All done”行沒有被執行? 馬拉松(100)
因為a >= 42
是真的,所以你這樣做:
return true;
...立即將控制轉移到finally
塊; 在finally
塊的末尾,函數返回( 不運行finally
塊后面的任何行)。 也就是說, return
不只是設置一個返回值,它在運行任何未完成的finally
塊之后終止該點的功能。
如果你想繼續執行,你可以寫一個變量然后在結尾處return
一個:
static boolean Marathon(int a) {
boolean rv = false;
try {
if (a < 0)
throw new NegativeException();
else if (a == 0)
throw new ZeroException();
else if (a >= 42)
rv = true;
} catch (ZeroException e) {
System.out.println("Use natural number");
} finally {
System.out.println("One last thing");
}
System.out.println("All done.");
return rv;
}
有關在try
和catch
return
更多內容:如果從具有finally
塊的try
中發出return
,它會立即將控制轉移到finally
塊。 當到達該塊的末尾時,該函數終止(在finally
塊之后 不運行任何代碼,除非您嵌套了finally
塊或類似的塊)。 如果你從一個catch
return
,也會發生同樣的事情。
例如:
try {
if (someCondition) {
return 1;
}
if (someOtherCondition) {
throw new Exception();
}
}
catch (Exception e) {
System.out.println("Got here because of exception");
return 2;
}
finally {
System.out.println("Got here");
}
System.out.println("May not have gotten here");
return 3;
無論如何, "Got here"
總會輸出; 這是finally
條款的重點,它們總是被執行。
如果someOtherCondition
為true(並且將在"Got here"
之前輸出),則只會輸出"Got here because of exception"
someOtherCondition
"Got here"
,在這種情況下,函數通常返回值1
。
如果someCondition
或someOtherCondition
為true,則不會輸出"May not have gotten here"
可能沒有someCondition
,因為try
和catch
塊中的return
s。
如果兩個條件都不成立,則會看到"May not have gotten here"
到達"May not have gotten here"
然后是"Got here"
到達"Got here"
,函數返回3
。
請注意, return
在catch
塊意味着該函數正常返回(值是2
),當someOtherCondition
是真實的,它不會拋出。 如果你沒有那里的return
而someOtherCondition
是真的,你會看到"Got here because of exception"
而"Got here"
和"Got here"
,然后函數將以throw結束(根本沒有返回值),並且不會輸出"May not have gotten here"
。
最后但並非最不重要的:如果你在finally
塊中有一個return
,那么return
“wins”:即使你已經在finally
塊中因為你已經發出了一個return
,finally塊中的一個return
取代它,函數返回finally
說的值,而不是早期的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.