Finally block executing before catch

c#, try-catch

Solution

As far as I understand try-catch-finally statement, just after exception is caught finally block gets executed.

No, that's wrong.

The `finally` block gets executed after either an applicable `catch` clause block has been executed, or immediately after the exception is thrown if no applicable `catch` exists. However, that only applies to `catch` and `finally` on the same `try` block -- if the exception is propagated, `finally` will run before any `catch` and/or `finally` that is further up the call stack.

How does this apply when function throws exception, like example below.

`foo` is called, it throws, and its `finally` block is executed. Since there was no `catch` the exception propagates and is caught inside `main`.

What if some resources are released in finally block which by initial exception could not be.

I do not understand the question.

Does this mean that finally block throws new (another) exception, overriding original exception.

Yes, that's how it works.

Problem

As far as I understand try-catch-finally statement, just after exception is caught finally block gets executed. How does this apply when function throws exception, like example below. What if some resources are released in finally block which by initial exception could not be. Does this mean that finally block throws new (another) exception, overriding original exception. I know that you can catch the exception that might be thrown in the try block of a try-finally statement higher up the call stack. That is, you can catch the exception in the method that calls the method that contains the try-finally statement (msdn documentation). ``` static void foo() { try { Console.WriteLine("foo"); throw new Exception("exception"); } finally { Console.WriteLine("foo's finally called"); } } static void Main(string[] args) { try { foo(); } catch (Exception e) { Console.WriteLine("Exception caught"); } } ``` Output: ``` foo foo's finally called Exception caught ```

Original source

Related problems