3

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();            
    }
}
Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
Tommy
  • 69
  • 4
  • I would recommend checking out the [MSDN article](https://msdn.microsoft.com/en-us/library/dszsf989.aspx) on this! It's brief, and has a nice example. – Will Ray Apr 21 '16 at 18:58
  • If your catch statement is designed to throw an exception out of the method, the finally block will still execute. Anything outside of the catch block will not. – Compass Apr 21 '16 at 18:59
  • As a best practice, you should not catch generally like this `catch {` as that removes the call stack but catch specific failures you can handle for a specific case. I refer to this as a "try hide" which I have seen some developers use to hide errors due to lack of skill in creation of problematic or challenging code specifically that does not follow good practices . – Mark Schultheiss Apr 22 '16 at 14:22

5 Answers5

8

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.

Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53
2

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

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
1

The finally block executes code that needs to be run in either case. For example, you frequently rethrow an exception or otherwise go to other code. If the cleanup code for resources is not in a finally block, it will not be executed. You could also put this code in the catch block, but then you would be repeating the code after the try block anyway.

Daniel Underwood
  • 2,191
  • 2
  • 22
  • 48
0

the finally block is incredibly helpful because it allows you to do resource clean up that otherwise wouldn't happen if you hit an exception.

e.g. (in pseudo)

try {
    open socket
    use socket
} 
// note: no catch for any socket exceptions
finally {
    delete socket  // always executed
}
  • you should maybe show what it would look like without finally, delete socket in both try and catch – Fredou Apr 21 '16 at 18:56
0

The whole point of the finally block is to wrap up stuff which you started. Suppose you opened a buffer in the try block, you shall close it in the finally. This is necessary so that even if an exception occurs and you exit from the try the resources are properly closed.

try
{
    //Do Something
}
catch
{
    //Catch Something
}
finally
{
    //Always Do This
}

A lot of times the code inside your catch statement will either rethrow an exception or break out of the current function. If you don't have a finally block, "Always Do this" call won't execute that is if the code inside the catch statement issues a return or throws a new exception.

Ani Menon
  • 27,209
  • 16
  • 105
  • 126