为什么在 C# 中使用 finally? [英] Why use finally in C#?

查看:42
本文介绍了为什么在 C# 中使用 finally?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

finally 块中的任何内容(几乎)总是被执行,那么将代码封闭在其中或不封闭有什么区别?

Whatever is inside finally blocks is executed (almost) always, so what's the difference between enclosing code into it or leaving it unclosed?

推荐答案

finally 块中的代码将被执行,无论是否有异常.当涉及到某些需要像关闭连接一样运行的内务处理功能时,这非常方便.

The code inside a finally block will get executed regardless of whether or not there is an exception. This comes in very handy when it comes to certain housekeeping functions you need to always run like closing connections.

现在,我猜测你的问题是为什么你应该这样做:

Now, I'm guessing your question is why you should do this:

try
{
    doSomething();
}
catch
{
    catchSomething();
}
finally
{
    alwaysDoThis();
}

何时可以这样做:

try
{
    doSomething();
}
catch
{
    catchSomething();
}

alwaysDoThis();

答案是很多时候,catch 语句中的代码要么重新抛出异常,要么跳出当前函数.使用后一个代码,alwaysDoThis();"如果 catch 语句中的代码发出返回或抛出新异常,则不会执行调用.

The answer is that a lot of times the code inside your catch statement will either rethrow an exception or break out of the current function. With the latter code, the "alwaysDoThis();" call won't execute if the code inside the catch statement issues a return or throws a new exception.

这篇关于为什么在 C# 中使用 finally?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆