Search code examples
c#exceptiontry-catch-finallyfinallytry-finally

Execution order of try, catch and finally block


Suppose I have some C# code like this:

try {
    Method1();
}
catch(...) {
    Method2();
}
finally {
    Method3();
}
Method4();
return;

My question is, provided no exception is thrown, will Method3() be executed before Method4(), or is it that the finally block is only executed before a return, continue or break statement?


Solution

  • Yes, the finally block of the try-catch will be executed in order as you would expect, and then execution will proceed onto the rest of the code (after completing the entire try-catch-finally block).

    You can think of the entire try-catch-finally block as a single component that would function just like any other method call would (with code being executed before and after it).

    // Execute some code here
    
    // try-catch-finally (the try and finally blocks will always be executed
    // and the catch will only execute if an exception occurs in the try)
    
    // Continue executing some code here (assuming no previous return statements)
    

    Example

    try 
    {
        Console.WriteLine("1");
        throw new Exception();
    }
    catch(Exception) 
    {
        Console.WriteLine("2");
    }
    finally 
    {
        Console.WriteLine("3");
    }
    Console.WriteLine("4");
    return;
    

    You can see an example of this in action here that yields the following output :

    1
    2
    3
    4