15

考虑以下代码:

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

如果something无效并且我从尝试中返回,代码是否@finally执行?我相信它应该,但我与之交谈过的其他人不这么认为,我目前无法对此进行测试。

4

5 回答 5

15

@finally 代码总是根据herehere执行。

@finally 块包含无论是否引发异常都必须执行的代码。

于 2010-06-03T19:30:46.713 回答
4

是的。奇怪的是,确实如此。我不知道为什么,但我只是建立了一个测试并尝试了一些配置,并且每次都这样做。

这是配置:

  • 在 try 块中返回:停止执行 try 块并导致 finally 被执行
  • 在 try 块中返回并在 finally 中返回:停止执行 try 并在 finally 块和整个方法中停止执行。
  • 在 finally 块中返回:功能类似于在 try/catch/finally 块之外的正常返回。
于 2010-06-03T19:32:42.490 回答
2

使用 RAI 定义,Finally 块无论如何都会在该代码范围内针对特定资源执行。

它与 Object's 有密切的关系~Destructor。与对象~Destructor总是执行一样,finally 块也会执行。

于 2013-04-04T08:41:21.283 回答
1

是的。即使有一个Exceptioninsidecatch块,finally也会被执行。

如果您熟悉 C++,只需将其finally视为. 无论对象中的语句处于何种状态,都将被执行。但是你不能放在[一些编译器允许] 之内。destructorobject~Destructorreturnfinally

请参阅下面的代码:查看如何y更改全局变量。另请参阅如何Exception1Exception2.

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
于 2013-03-06T09:19:18.343 回答
0

是的,这是一个示例片段,输出是

尝试!抓住!最后!

@try {
    NSLog(@"try!");

    NSException *e = [NSException
                      exceptionWithName:@"No Name"
                      reason:@"No Reason"
                      userInfo:nil];
    @throw e;


} @ catch (...)
{
    NSLog(@"catch!");
    return;
}
@finally
{
    NSLog(@"finally!");
}

NSLog (@"other code");
于 2018-04-04T04:44:09.940 回答