#911 – finally Block Execution When Exception Is Rethrown
August 19, 2013 1 Comment
Recall that if an exception is caught in a catch block, an associated finally block will execute after the execution of the catch block.
If the catch block rethrows the exception, the finally block will execute after the catch block, but before the exception propagates back up the call stack.
In the example below, the sequence is:
- Exception thrown from try block in HelperMethod
- Exception caught in catch block in HelperMethod, catch block executes up to throw
- finally block in HelperMethod executes
- Exception caught in catch block of Main method
static void Main(string[] args) { try { HelperMethod(); } catch { Console.WriteLine("Caught exception in Main()"); } Console.ReadLine(); } static void HelperMethod() { try { throw new ApplicationException("Uh-oh"); } catch { Console.WriteLine("In catch block, before re-throwing"); throw; } finally { Console.WriteLine("In finally block"); } }