這篇文章帶給大家的內容是關於Java中finally與return的執行順序解析(程式碼範例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。
都知道,finally的執行特點
##1、不管有木有出現異常,finally區塊中程式碼都會執行;2、當try和catch中有return時,finally仍然會執行。 那麼問題來了,執行順序是怎麼樣的呢? 一個簡單的測試類別及反編譯後的字節碼:public class Test { publicstatic void main(String[] args) { System.out.println(test()); } publicstatic int test() { try{ System.out.println("Codesin try block."); return0; }catch (Exception e) { System.out.println("Codesin catch block."); return100; }finally { System.err.println("Codesin finally block."); } } } /* public static int test(); Code: 0: getstatic #2 // Fieldjava/lang/System.out:Ljava/io/PrintStream; 3: ldc #5 // String Codes in try block. 5: invokevirtual #6 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 8: iconst_0 9: istore_0 10: getstatic #7 // Field java/lang/System.err:Ljava/io/PrintStream; 13: ldc #8 // String Codes in finallyblock. 15: invokevirtual #6 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 18: iload_0 19: ireturn 20: astore_0 21: getstatic #2 // Fieldjava/lang/System.out:Ljava/io/PrintStream; 24: ldc #10 // String Codes in catchblock. 26: invokevirtual #6 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 29: bipush 100 31: istore_1 32: getstatic #7 // Fieldjava/lang/System.err:Ljava/io/PrintStream; 35: ldc #8 // String Codes in finallyblock. 37: invokevirtual #6 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 40: iload_1 41: ireturn 42: astore_2 43: getstatic #7 // Fieldjava/lang/System.err:Ljava/io/PrintStream; 46: ldc #8 // String Codes in finallyblock. 48: invokevirtual #6 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 51: aload_2 52: athrow */
try{ return; }catch(){} finally{} return;
測試程式碼:1.基本資料型別public static int test1(){ int a = 10; try{ a = 20; return a; }catch(Exception e){ //other codes. }finally{ a += 5; //other codes. } return a; }//最终返回值为20
public static StringBuffer test2(){ StringBuffer sb = new StringBuffer("abc"); try{ return sb; }catch(Exception e){ //other codes. }finally{ sb.append("DEF"); //other codes. } return sb; }//最终返回中内容为abcDEF
public static StringBuffer test3(){ StringBuffer sb = new StringBuffer("abc"); try{ return sb; }catch(Exception e){ //other codes. }finally{ sb = new StringBuffer("DEF"); //other codes. } return sb; }//最终返回值中的内容为abc
public static int test(int num){ int a = 10; try{ return a; }catch(ArithmeticException e){ a = 20; return a; }finally{ a = 30; return a; } }
Java中try與finally以及return語句的執行順序
以上是Java中finally與return的執行順序解析(程式碼範例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!