Why isn't the line "Console.WriteLine("asdf");" executed? All the others are. Shouldn't it also be as we can't jump out from the finally scope?
static bool Func() { try { try { } finally { try { throw new ApplicationException(); } finally { Console.WriteLine("asd"); } Console.WriteLine("asdf"); } } finally { Console.WriteLine("asd"); } }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With