try catch finally執行順序


大家都知道
try{
}chatch(){
}finally{
}
是java中異常處理最常見的一種方法,面試中也經常會考到這方面的知識,我也看了無數遍,但總是很容易忘記,也許寫出來會記憶深刻些吧.
假設try塊中一個return語句的話,那么catch和finally中的代碼還會執行嗎?如果會執行,那么順序又是什么?我寫了個測試類分別測試了以上問題:
測試一:
class Test22
{
public static String test(){
try{
//throw new Exception();
return "return";
}catch(Exception e){
System.out.println("catch");
}finally{
return "finally";
}
}
public static void main(String[] args)
{
System.out.println(test());
}
}
輸出結果為:finally
這說明finally先執行,其實我這也可以通過理解return的意義來理解這個順序,return是指跳出這個語句塊,跳出了自然不能回來再執行里面的語句了,而finally又是必須執行的,所以在跳出之前還是讓finally執行完吧.

測試二:
class Test22
{
public static String test(){
try{
throw new Exception();

}catch(Exception e){
System.out.println("catch");
}finally{
return "finally";
}
}
public static void main(String[] args)
{
System.out.println(test());
}
}
輸出結果:
catch
finally
這就是平常最常見的順序了,try中勢力出了異常,那么就是catch中執行了,然后就是finally里的語句了.
測試三:
class Test22
{
public static String test(){
try{
throw new Exception();
}catch(Exception e){
return "catch";
}finally{
return "finally";
}
}
public static void main(String[] args)
{
System.out.println(test());
}
}
輸出結果:
finally
在catch中有return和try塊中有return是一樣的情況了.


這次我應該是理解得比較透徹了,希望不要忘記了.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM