在 Objective-C 中,finally 中的代码在返回后是否会运行?
考虑以下代码:
@try {
if (something.notvalid)
{
return;
}
// do something else
} @catch (NSException *ex) {
// handle exception
} @finally {
NSLog(@"finally!");
}
如果 something
无效并且我从 try 中返回,则 @finally
中的代码是否执行?我相信应该如此,但与我交谈过的其他人并不这么认为,而且我目前无法对此进行测试。
Consider the following code:
@try {
if (something.notvalid)
{
return;
}
// do something else
} @catch (NSException *ex) {
// handle exception
} @finally {
NSLog(@"finally!");
}
If something
is not valid and I return from within the try, does the code in @finally
execute or not? I believe that it should but others I've spoken to don't think so and I'm unable to test this at the moment.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
@finally 代码始终根据此处 和此处。
@finally code always executes according to here and here.
是的。奇怪的是,确实如此。我不知道为什么,但我只是构建了一个测试并尝试了多种配置,每次都如此。
配置如下:
Yes. Oddly enough, it does. I'm not sure why, but I just built a test and tried a number of configurations and every time it did.
Here were the configs:
通过 RAI 定义,对于特定资源,Finally 块无论如何都会在该代码范围内执行。
它与Object的
~Destructor
含义相近。就像对象的~Destructor
总是执行一样,finally 块也会执行。With the RAI definition, Finally block will anyhow executed with that code scope, for particular resource.
It has a close meaning with Object's
~Destructor
. As same as an object's~Destructor
always executes, finally block also executes.是的。即使在
catch
块中出现Exception
,finally
也会被执行。如果您熟悉 C++,只需将
finally
视为对象
的析构函数
。无论对象内的语句处于什么状态,~Destructor
都将被执行。但是你不能将
return
放在finally
中[尽管有些编译器允许]。请参阅下面的代码:查看全局变量 y 是如何更改的。
另请参阅
Exception1
如何被Exception2
覆盖。输出:
Yes. Even if there was an
Exception
withincatch
block,finally
will be executed.If you are familiar with C++, just think
finally
as thedestructor
of anobject
. What ever the state of a statement within the object,~Destructor
will be executed.But you cant put
return
withinfinally
[some compilers allow though].See the code below: See how global variable
y
been changed.Also see how
Exception1
been covered byException2
.output:
是的,这是一个示例片段,输出是
try!
抓住!
最后!
Yes, here is a sample snippet, the output is
try!
catch!
finally!