为什么这个“终于”了? 执行?
如果运行下面的代码,它实际上会在每次调用 goto 后执行 finally:
int i = 0;
Found:
i++;
try
{
throw new Exception();
}
catch (Exception)
{
goto Found;
}
finally
{
Console.Write("{0}\t", i);
}
为什么?
If you run the code below it actually executes the finally after every call to the goto:
int i = 0;
Found:
i++;
try
{
throw new Exception();
}
catch (Exception)
{
goto Found;
}
finally
{
Console.Write("{0}\t", i);
}
Why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
以下文本来自C# 语言规范 (8.9.3 goto 语句)
goto 语句的执行方式如下:
The following text comes from the C# Language Specification (8.9.3 The goto statement)
A goto statement is executed as follows:
为什么你期望它不执行?
如果您有 try/catch/finally 或 try/finally 块,则无论 try 或 catch 块中包含什么代码,finally 块都会执行
大多数时候。考虑“return”而不是“goto”。
Why do you expect it to not execute?
If you have try/catch/finally or try/finally block, finally block executes
no matter what code you may have in the try or catch blockmost of the time.Instead of goto, consider 'return'.
给出的答案的要点 - 当控制通过任何方式离开受保护区域时,无论是“返回”,“转到”,“中断”,“继续”还是“抛出”,“最终”都会被执行 - 是正确的。 然而,我注意到几乎每个答案都说“finally 块总是运行”。 finally 块并不总是运行。在很多情况下,finally 块不会运行。
谁想尝试将它们全部列出来?
The gist of the answers given - that when control leaves the protected region via any means, whether "return", "goto", "break", "continue" or "throw", the "finally" is executed - is correct. However, I note that almost every answer says something like "the finally block always runs". The finally block does NOT always run. There are many situations in which the finally block does not run.
Who wants to try to list them all?
看起来很合理。
finally
块始终在try
或catch
之后运行。同样,
将始终运行
finally
块。 编辑 - 但请参阅上面埃里克的评论。Seems reasonable. A
finally
block is always run after either thetry
or thecatch
.Similarly
will always run the
finally
block. EDIT - but see Eric's comments above.这是设计使然。 在异常处理程序中,您可以采取一些特定于异常的操作。 在finally 块中,您应该进行资源清理——这就是为什么无论异常处理代码是什么,finally 块总是被执行的原因。
That's by design. In the exception handler you can take some exception-specific action. In the finally block you should do resource cleanup - that's why the finally block is always executed no matter what the exception handling code is.
正如人们所提到的,无论程序流程如何,
finally
都会运行。 当然,finally
块是可选的,因此如果不需要它,就不要使用它。As people have mentioned,
finally
runs no matter the program flow. Of course, thefinally
block is optional, so if you don't need it, don't use it.因为
finally
语句预计在离开try
(或捕获异常时的catch
)后执行。 这包括当您拨打 goto 电话时。Because a
finally
statement is expected to execute after leaving thetry
(orcatch
when an exception is caught). This includes when you make your goto call.这就是
finally
块的要点。 它总是执行(几乎)。That is the point of the
finally
block. It always executes (pretty much).