2010-06-03 43 views
15

考慮下面的代碼:在Objective-C中返回後,最終是否會運行代碼?

@try { 
    if (something.notvalid) 
    { 
    return; 
    } 
    // do something else 
} @catch (NSException *ex) { 
    // handle exception 
} @finally { 
    NSLog(@"finally!"); 
} 

如果something是無效的,我在嘗試內返回,並在@finally代碼執行或不?我相信它應該,但我所說的其他人不這麼認爲,目前我無法對此進行測試。

回答

14

@最終代碼總是按照herehere執行。

甲@finally塊包含一個異常 是否被拋出或不是 必須執行的代碼。

4

是的。奇怪的是,它確實如此。我不知道爲什麼,但我只是建了一個測試,並嘗試了一些配置,每次都做了。

這裏是在CONFIGS:

  • 在try塊返回:停止try塊的執行,並在try塊導致最後被執行
  • 返回,返回在最後:停止嘗試的執行和停止執行在最後阻止和整個方法。
  • 在finally塊中返回:像try/catch/finally塊之外的正常返回一樣運行。
+2

第一個案例並不奇怪。這就是'終於'的意義。請參閱http://stackoverflow.com/questions/65035/in-java-does-return-trump-finally。 – kennytm 2010-06-03 19:38:49

+0

你看,我期望'return'超出try/catch/finally'塊的範圍並應用於該方法。我並不是說這樣做是錯誤的,但它讓我無法理解。這只是我從未關注過的東西。我想我一直把我的方法一直貫徹到最後;) – lewiguez 2010-06-03 19:51:53

1

是的。即使在catch區塊內有Exceptionfinally也會執行。

如果您熟悉C++,請將finally設爲objectdestructor。對象中的聲明狀態~Destructor將被執行。 但是你不能把return放在finally [儘管有些編譯器允許]。

請參閱下面的代碼:查看如何更改全局變量y。 另請參閱Exception1如何覆蓋Exception2

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace finallyTest 
{ 
    class Program 
    { 
     static int y = 0; 
     static int testFinally() 
     { 
      int x = 0; 
      try 
      { 
       x = 1; 
       throw new Exception("Exception1"); 
       x = 2; 
       return x; 
      } 
      catch (Exception e) 
      { 
       x = -1; 
       throw new Exception("Exception2", e); 
      } 
      finally 
      { 
       x = 3; 
       y = 1; 
      } 
      return x; 
     } 

     static void Main(string[] args) 
     { 
      try 
      { 
       Console.WriteLine(">>>>>" + testFinally()); 
      } 
      catch (Exception e) 
      { Console.WriteLine(">>>>>" + e.ToString()); } 
      Console.WriteLine(">>>>>" + y); 
      Console.ReadLine(); 
     } 
    } 
} 

輸出:

>>>>>System.Exception: Exception2 ---> System.Exception: Exception1 
    at finallyTest.Program.testFinally() in \Projects\finallyTest\finallyTest\Program.cs:line 17 
    --- End of inner exception stack trace --- 
    at finallyTest.Program.testFinally() in \Projects\finallyTest\finallyTest\Program.cs:line 24 
    at finallyTest.Program.Main(String[] args) in \Projects\finallyTest\finallyTest\Program.cs:line 38 
>>>>>1 
2

隨着RAI定義,最後塊將無論如何與該代碼範圍,對於特定的資源執行。

它與Object的~Destructor有密切的含義。如同一個對象的~Destructor總是執行,最後block也會執行。

相關問題