Nested try-finally in C#

Finally blocks only guarantee (at least mostly guarantee, see excerpt from MSDN below) that they will be entered in the event that the try block throws an exception. If you throw an exception within the finally block, the exception will cause control to leave the finally block and the rest of the code within that finally block will not execute.

In your case, the line that isn't being executed is occurring after an exception in the same finally block, so it gets skipped.

From MSDN - try-finally:

The finally block is useful for cleaning up any resources that are allocated in the try block, and for running any code that must execute even if an exception occurs in the try block. Typically, the statements of a finally block are executed when control leaves a try statement, whether the transfer of control occurs as a result of normal execution, of execution of a break, continue, goto, or return statement, or of propagation of an exception out of the try statement.

Within a handled exception, the associated finally block is guaranteed to be run. However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered. That, in turn, is dependent on how your computer is set up. For more information, see Unhandled Exception Processing in the CLR.

Note: Unhandled Exception Processing in the CLR is a reference to an article in the September 2008 issue of the MSDN Magazine. All 2008 and older issues of MSDN Magazine are only available as .chm files, and will need to be downloaded before viewing.


I think the best way this could be answered is by using the code and hence the following image enter image description here


Because the exception is being thrown in that finally block, so it causes control to fall out to the final finally block. So the "asdf" WriteLine never executes.

Tags:

C#

Try Catch