Why use Finally in Try ... Catch

45,267

Solution 1

Yes, it is different. Finally will always run (barring program crash). If the function exits inside of the try catch block, or another error is thrown in either the try or the catch, the finally will still execute. You won't get that functionality not using the finally statement.

Solution 2

Code with four radio buttons:

  • Return in TRY
  • Return in CATCH
  • Throw in CATCH
  • Finish CATCH

    private void checkFinally()
    {
        try
        {
            doFinally();
        }
        catch
        {
            Console.WriteLine(" Breaking news: a crash occured. ");
        }
    }
    
    private void doFinally()
    {
        Console.WriteLine(" ");
        Console.Write("Here goes: " 
            + (radioReturnInTry.Checked ? "2. Return in try: " 
                    : (radioReturnInCatch.Checked? "3. Retrun in catch: "
                        : (radioThrowInCatch.Checked? "4. Throw in catch: "
                            : "1. Continue in catch: "))) );
        try
        {
            if (radioReturnInTry.Checked)
            {
                Console.Write(" Returning in try. ");
                return;
            }
            Console.Write(" Throwing up in try.  ");
            throw new Exception("check your checkbox.");
        }
        catch (Exception ex)
        {
            Console.Write(" ...caughtcha! ");
            if (radioReturnInCatch.Checked)
            {
                Console.Write("Returning in catch. ");
                return;
            }
            if (radioThrowInCatch.Checked)
            {
                Console.Write(" Throwing up in catch. ");
                throw new Exception("after caught");
            }
        }
        finally { Console.Write(" Finally!!"); }
        Console.WriteLine(" Done!!!"); // before adding checkboxThrowInCatch, 
        // this would never happen (and was marked grey by ReSharper)
    
    }
    

Output:

  • Here goes: 1. Continue in catch: Throwing up in try. ...caughtcha! Finally!! Done!!!
  • Here goes: 2. Return in try: Returning in try. Finally!!
  • Here goes: 3. Retrun in catch: Throwing up in try. ...caughtcha! Returning in catch. Finally!!
  • Here goes: 4. Throw in catch: Throwing up in try. ...caughtcha! Throwing up in catch. Finally!! Breaking news: a crash occured.

To summarize: Finally takes care of two things:

  1. Of code that returned in the try or in the catch.
  2. Or If you had an exception in the try, AND THROW an exception in the catch,
  3. or, if you had an exception in the try, AND DID NOT CATCH that exception,

Finally to summarize "FINALLY": Finally does nothing special if you tried,and

  1. DID NOT RETURN,
  2. and caught any exceptions during the trial, and then
  3. DID NOT RETURN in the catch either, and
  4. DID NOT THROW or have code that throws up.

And last but not least (finally): If you have an exception in your code that YOU DID NOT CATCH, your code will fly, WITHOUT REACHING THE FINALLY.

Hope this is clear. (Now it is to me...)

Moshe

Solution 3

Finally contains code that needs to be evaluated at all conditions [whether or not an exception occurred].

There is no way to exit a try block without executing its finally block. If the finally block exists, it always executes. (This statement is true for all intents and purposes. There is a way to exit a try block without executing the finally block. If the code executes a System.exit(0); from within a try block, the application terminates without the finally executing. On the other hand, if you unplug the machine during a try block, the finally will not execute either.)

The main use is for disposing objects. It will be useful when you want to close user defined resources like file , opened resources(db stmts).

Edit

Also finally won't be executed after a stackoverflow exception.

Solution 4

The difference is when the code in the try block throws an exception that isn't caught by the catch block.

Normally a catch block would catch a specific type of exception, and let anything else through. In that case, the finally block will still run.

The finally block will also run if the code in the try block returns.

Solution 5

This is a good idea when dealing with database connections or anytime objects need to be disposed of. Just in case something goes wrong while running queries, you can still close the connection safely. It also helps to clean up code that the block outside the try/catch/finally block is not able to access.

Share:
45,267
awe
Author by

awe

I am a senior software developer. I am interested in web programming (Javascript, CSS, Vue.js, React.js) and GUI design. Also .NET programming (C#, VB).

Updated on July 08, 2022

Comments

  • awe
    awe almost 2 years

    I see that the Finally in Try .. Catch will always execute after any parts of the execution of the try catch block.

    Is it any different to just skip the Finally section and just run it after, outside the try catch block?

    Example 1, Try ... Catch ... Finally ... End Try

        Try
            'Do something
        Catch ex As Exception
            'Handle exception
        Finally
            'Do cleanup
        End Try
    

    Example 2, Try ... Catch ... End Try ... Do the finally stuff outside

        Try
            'Do something
        Catch ex As Exception
            'Handle exception
        End Try
        'Do cleanup