2014-02-27 36 views
2

在下面的代碼我想了解return陳述的行爲。 Finally塊會一直執行這樣此函數始終return 30,但究竟是在嘗試block.Does return語句的意義這回在try塊返回值,它的調用者,這將在一定堆棧這個值存儲和更換時,看一回在finally塊中聲明?或者在try塊中返回將調用finally塊?行爲嘗試捕捉回報的最後

public static int test() { 
    try { 
      return 10;// to whom this 10 is returned to? 
    } catch (Exception e) { 
     return 20; 
    }finally{ 
      System.out.println("Finally"); 
     return 30; 
    } 
} 

在此先感謝。

+0

可能重複的[爲什麼打印1?](http://stackoverflow.com/questions/19651860/why-is-printed-1) – SudoRahul

+0

正如警告:'finally'是爲了清理資源和不用於控制流。請參閱http://stackoverflow.com/questions/48088/returning-from-a-finally-block-in-java以及從那裏鏈接的主題以獲取更多詳細信息。 – CompuChip

回答

1

兩個1030會回來。但是30是在stack(最上面的元素)的上方。所以來電者獲得返回值爲30

0

由於finally塊總是在您的情況下執行以清理資源,因此它將位於堆棧頂部,所以ouptut將爲30。但是,如果你想走出你的try塊的直接,那麼你可以使用System.exit()

1

finally塊應該用於資源只有清除,例如

public static int test() { 
    MyResource resource = null; 

    try { 
     // resource allocation 
     MyResource resource = MyResource.allocate(); 

     ... // do something with the resource 

     return 10; // <- Normal flow 
    } 
    catch(MyResourceException e) { 
     ... // something was wrong with resource 

     return 20; // <- Abnormal, but expected flow 
    } 
    finally { 
     // In any case - has an exception (including errors) been thrown or not 
     // we have to release allocated resource 

     // The resource has been allocated 
     if (resource != null) 
     resource.release(); 

     // no return here: finally is for resource clearing only 
    } 
    } 

的情況下,你把return 30到最後兩個值(比如,1030)將 放堆放;但由於30將是在棧上,你會看到30頂部。