When is finally run if you throw an exception from the catch block?

Viewed 72599
try {
   // Do stuff
}
catch (Exception e) {
   throw;
}
finally {
   // Clean up
}

In the above block when is the finally block called? Before the throwing of e or is finally called and then catch?

8 Answers

You can do it, I have done this to ensure cleanup.

using System;
class Program
{
static void Main()
{
    FinallyThrow();
    Console.ReadLine();
}
static void FinallyThrow()
{
    // Get finally block to execute EVEN IF there is an unhandled exception
    Exception thrownEx = null;
    try
    {
        Console.WriteLine("try..");
        throw new InvalidOperationException();
    }
    catch (Exception ex)
    {
        Console.WriteLine("catch..");
        thrownEx = ex;
    }
    finally
    {
        Console.WriteLine("finally..");
        if (thrownEx != null) throw thrownEx;
    }
}
}

OUTPUT (after breaking to the unhandled exception)

try..
catch..
finally..

.Finally always run even if unhandled exception

Related