通过 catch 块从函数返回,finally 块会发生什么?

发布于 2024-10-06 18:28:14 字数 274 浏览 6 评论 0原文

我已经尝试了catchfinally块,如果发生一些异常我将从catch块返回,所以finally块仍然被执行,如果是这样,什么时候?回国前还是回国后?

这是正确的做法吗?

try
{
// do something
}

catch (Exception)
{    
  return false;
}
finally
{
  if (connection.State == ConnectionState.Open) connection.Close();
}

I've try catch finally block and if some exception occurs I'll return from the catch block, so finally block is still executed, if so, when? Before return or after return?

Is this the right practice?

try
{
// do something
}

catch (Exception)
{    
  return false;
}
finally
{
  if (connection.State == ConnectionState.Open) connection.Close();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

碍人泪离人颜 2024-10-13 18:28:15

返回后它将执行“finally”块。 “最后”用于一些实践,例如关闭数据库连接(总是需要完成)

It will execute "finally" block after return. "Finally" is used for some practice such as close database connection (always need to be done)

双手揣兜 2024-10-13 18:28:15

finally 块总是被执行。在您的情况下,它在您的 return 语句之前执行。

finally block is always executed. In your case it is executed before your return statement.

夏日落 2024-10-13 18:28:15

你可以自己尝试一下

private bool test()
    {
        try
        {
            int i = 0;
           int u = 10 / i;
        }

        catch (Exception)
        {
            return false;
        }
        finally
        {

        }
        return true;
    }

,这是一个被零除的异常。当你执行这段代码时,finally将执行,return后将执行。

它类似于运行时在finally块的情况下返回的结果!

You can try with your self

private bool test()
    {
        try
        {
            int i = 0;
           int u = 10 / i;
        }

        catch (Exception)
        {
            return false;
        }
        finally
        {

        }
        return true;
    }

so it is a divideby zero exception. When you execute this code , finally will execute and after return will execute.

it is something like Runtime the returned result in case of finally block!

若水般的淡然安静女子 2024-10-13 18:28:15

finally 块始终会在代码退出 try-catch-finally 块之前执行(任何阻止 finally 块执行的条件,如 ThreadAbortException,都会阻止代码退出 try-catch-finally 块)。

A finally block will always execute before the code exits a try-catch-finally block (any condition like a ThreadAbortException which prevents the finally block from executing will prevent code from exiting the try-catch-finally block).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文