Why use finally in C#?

2020-01-24 03:22发布

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

13条回答
干净又极端
2楼-- · 2020-01-24 03:55

Ahh...I think I see what you're saying! Took me a sec...you're wondering "why place it in the finally block instead of after the finally block and completely outside the try-catch-finally".

As an example, it might be because you are halting execution if you throw an error, but you still want to clean up resources, such as open files, database connections, etc.

查看更多
叼着烟拽天下
3楼-- · 2020-01-24 03:58

Finally statements can execute even after return.

private int myfun()
{
    int a = 100; //any number
    int b = 0;
    try
    {
        a = (5 / b);
        return a;
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
        return a;
    }

 //   Response.Write("Statement after return before finally");  -->this will give error "Syntax error, 'try' expected"
    finally
    {
      Response.Write("Statement after return in finally"); // --> This will execute , even after having return code above
    } 

    Response.Write("Statement after return after finally");  // -->Unreachable code
}
查看更多
forever°为你锁心
4楼-- · 2020-01-24 04:05

Because finally will get executed even if you do not handle an exception in a catch block.

查看更多
Root(大扎)
5楼-- · 2020-01-24 04:07

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();
}

When you can do this:

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

alwaysDoThis();

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.

查看更多
该账号已被封号
6楼-- · 2020-01-24 04:07

finally, as in:

try {
  // do something risky
} catch (Exception ex) {
  // handle an exception
} finally {
  // do any required cleanup
}

is a guaranteed opportunity to execute code after your try..catch block, regardless of whether or not your try block threw an exception.

That makes it perfect for things like releasing resources, db connections, file handles, etc.

查看更多
闹够了就滚
7楼-- · 2020-01-24 04:11

Say you need to set the cursor back to the default pointer instead of a waiting (hourglass) cursor. If an exception is thrown before setting the cursor, and doesn't outright crash the app, you could be left with a confusing cursor.

查看更多
登录 后发表回答