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条回答
Rolldiameter
2楼-- · 2020-01-24 04:16

As mentioned in the documentation:

A common usage of catch and finally together is to obtain and use resources in a try block, deal with exceptional circumstances in a catch block, and release the resources in the finally block.

It is also worth reading this, which states:

Once a matching catch clause is found, the system prepares to transfer control to the first statement of the catch clause. Before execution of the catch clause begins, the system first executes, in order, any finally clauses that were associated with try statements more nested that than the one that caught the exception.

So it is clear that code which resides in a finally clause will be executed even if a prior catch clause had a return statement.

查看更多
登录 后发表回答