In C# will the Finally block be executed in a try,

2019-01-06 14:03发布

10条回答
Root(大扎)
2楼-- · 2019-01-06 14:36

Straight from MSDN:

The finally block is useful for cleaning up any resources allocated in the try block. Control is always passed to the finally block regardless of how the try block exits.

Whereas catch is used to handle exceptions that occur in a statement block, finally is used to guarantee a statement block of code executes regardless of how the preceding try block is exited.

http://msdn.microsoft.com/en-us/library/zwc8s4fz(VS.71,loband).aspx

查看更多
混吃等死
3楼-- · 2019-01-06 14:36

Finally block is guaranteed to be executed in any case.

查看更多
贪生不怕死
4楼-- · 2019-01-06 14:38

Finally will happen everytime for that try catch block

查看更多
Juvenile、少年°
5楼-- · 2019-01-06 14:38

Finally is always executed. I not depends on how the try block works. If u have to do some extra work for both try and cath, it is better to put in finally block. So you can gurantee that it is always executed.

查看更多
成全新的幸福
6楼-- · 2019-01-06 14:39

Generally the finally block is always executed regardless of whether an exception is thrown or not and whether any exception is handled or not.

There are a couple of exceptions (see other answers for more details).

查看更多
时光不老,我们不散
7楼-- · 2019-01-06 14:41

finally is executed most of the time. It's almost all cases. For instance, if an async exception (like StackOverflowException, OutOfMemoryException, ThreadAbortException) is thrown on the thread, finally execution is not guaranteed. This is why constrained execution regions exist for writing highly reliable code.

For interview purposes, I expect the answer to this question to be false (I won't guarantee anything! The interviewer might not know this herself!).

查看更多
登录 后发表回答