2015-06-02 25 views
5

感到困惑的是如何最終關鍵字實際工作...最後工作不正常

try塊運行到完成它返回到哪裏被調用的 方法之前。但是,在它返回到調用方法 之前,finally塊中的代碼仍然執行。因此,請記住 finally塊中的代碼仍將執行,即使在try塊中某處存在返回語句 。

當我運行的代碼

,我得到5而不是10如我所料

public class Main { 

    static int count = 0; 
    Long  x; 
    static Dog d  = new Dog(5); 

    public static void main(String[] args) throws Exception { 
     System.out.println(xDog(d).getId()); 
    } 

    public static Dog xDog(Dog d) { 

     try { 
      return d; 
     } catch (Exception e) { 
     } finally { 
      d = new Dog(10); 

     } 
     return d; 

    } 
} 

public class Dog { 

    private int id; 

    public Dog(int id) { 
     this.id = id; 
    } 

    public int getId() { 
     return id; 
    } 

} 
+1

http://stackoverflow.com/questions/65035/does-finally-always-execute-in-java –

+0

finally語句在執行完return語句之後執行,這就是爲什麼你得到5個不是10 –

回答

9

finally塊不return語句,但實際收益之前之前執行。這意味着return語句中的表達式在執行finally塊之前被評估。在您的情況下,當您編寫return d時,將對d表達式進行評估並存儲到寄存器中,然後finally被執行並返回該寄存器的值。沒有辦法改變該寄存器的內容。

+2

如果Dog類有一個setter,他會在'finally'中執行'd.setId(10)',他會改變Dog的值 – Loki

0

您的代碼確實工作正常,語句在finally塊中運行。你沒有得到10的唯一原因是你沒有返回你設置finally塊的值。 finally塊之外的代碼不會運行,因爲它已經在try塊中返回它。爲了讓你的代碼正常工作,只需將你的xDog方法更改爲此。

public static Dog xDog(Dog d) 
{ 
    try 
    { 
     return d; 
    } 
    catch (Exception e) 
    { } 
    finally 
    { 
     d = new Dog(10); 
     return d; 
    } 
} 

我希望這對你有幫助。