Search code examples
c#.nettry-catch-finally

Explain "finally"'s use in try-catch-finally blocks


I read that finally key make a try-catch block final work, even function throw exception or not. But I wonder what is different if I don't put a code inside a finally block (like Function_2 below), which is the way I'm using to coding. Thank You!

void Function_1()
{
    try
    {
        throw new Exception();
    }
    catch
    {
    }
    finally                                   //Have finally block
    {
        Other_Function();
    }
}

void Function_2()
{
    try
    {
        throw new Exception();
    }
    catch
    {
    }

    Other_Function();                        //Don't have finally block
}

Solution

  • if I dont put a code inside a finally block (like Function_2 below)

    if you don't put code inside finally , until unless you won't get an exception that code block will be executed.

    but if you get an exception before that code block (which was not kept inside finally) will not be executed as the control returns from there itself.

    but if you keep your code in finally , it will be executed irrespective of the situation.

    Example:1 without finally block

     try
        {
        //throw exption
        }
        catch
        {
        //return from here
        }
    
        //below statement won't get executed
        Other_Function(); 
    

    Example:2 with finally block

      try
        {
        //throw exption
        }
        catch
        {
        //return from here if finally block is not available 
        //if available execute finally block and return
        }
        finally
        {
        //below statement surly gets executed
        Other_Function(); 
        }