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

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

问题描述

无论是内部的finally块被执行(几乎)总是,那么什么是包code进去或离开之间的区别是没有结束的?

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

推荐答案

finally块内的code将获得无论是否有一个例外执行。这是非常方便的,当涉及到你需要总是喜欢关闭连接运行某些内务功能。

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语句里面的code要么重新抛出异常或打破当前的功能。后者code时,alwaysDoThis();如果catch语句里面的code问题退货或抛出一个新的异常呼叫将不会执行。

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#中最后使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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