Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the finally block pointless? [duplicate]

I'm teaching myself C# and I am up to studying the try, catch and finally. The book I'm using is discussing how the finally block runs regardless of whether or not the try block is successful. But, wouldn't code that is written outside of the catch block be run anyway even if it wasn't in finally? If so, what's the point of finally? This is the example program the book is providing:

class myAppClass
{
    public static void Main()
    {
        int[] myArray = new int[5];

        try
        {
            for (int ctr = 0; ctr <10; ctr++)
            {
                myArray[ctr] = ctr;
            }
        }
        catch
        {
            Console.WriteLine("Exception caught");
        }
        finally
        {
            Console.WriteLine("Done with exception handling");
        }
        Console.WriteLine("End of Program");
        Console.ReadLine();            
    }
}
like image 622
Tommy Avatar asked Oct 20 '25 04:10

Tommy


2 Answers

These are scenarios where a finally is useful:

try
{
    //Do something
}
catch (Exception e)
{
    //Try to recover from exception

    //But if you can't
    throw e;
}
finally
{
    //clean up
}

Usually you try to recover from exception or handle some types of exceptions, but if you cannot recover of you do not catch a specific type of exception the exception is thrown to the caller, BUT the finally block is executed anyway.

Another situation would be:

try
{
    //Do something
    return result;
}
finally
{
    //clean up
}

If your code runs ok and no exceptions is thrown you can return from the try block and release any resources in the finally block.

In both cases if you put your code outside the try, it will never be executed.

like image 103
Arturo Menchaca Avatar answered Oct 22 '25 18:10

Arturo Menchaca


Here is a simple example to show code that is written outside of the catch block does not run anyway even if it wasn't in finally!

try
{
    try { throw new Exception(); }
    finally { Console.WriteLine("finally"); }
    Console.WriteLine("Where am I?");
}
catch { Console.WriteLine("catched"); }

and the output is

finally
catched

Please read the MSDN

like image 43
Hamid Pourjam Avatar answered Oct 22 '25 20:10

Hamid Pourjam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!