Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use Finally in Try ... Catch

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
like image 562
awe Avatar asked Jul 21 '09 11:07

awe


People also ask

Why is finally needed in try catch?

The try statement defines the code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error.

Is finally mandatory in try catch?

Yes you can write try without catch. In that case you require finally block. Try requires either catch or finally or both that is at least one catch or finally is compulsory.

What is the purpose of finally?

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

What does finally do in try catch Java?

What Is finally? finally defines a block of code we use along with the try keyword. It defines code that's always run after the try and any catch block, before the method is completed. The finally block executes regardless of whether an exception is thrown or caught.


11 Answers

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.

like image 116
kemiller2002 Avatar answered Oct 01 '22 10:10

kemiller2002


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

like image 27
3 revs Avatar answered Sep 30 '22 10:09

3 revs


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.

like image 35
RichieHindle Avatar answered Oct 01 '22 10:10

RichieHindle


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.

like image 27
rahul Avatar answered Sep 30 '22 10:09

rahul


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.

like image 22
scheibk Avatar answered Oct 03 '22 10:10

scheibk


The Finally block will execute regardless of if the function exits because of an exception. (there are some exceptions to this rule, see this stackoverflow question for more info).

For example:

Try
    'Do something
Catch ex As Exception
    if 'Some Condition
       throw ex
    else
       'Handle exception
Finally
    'Do cleanup
End Try

In this case the Finally block will still be executed even though you may throw an exception out of the function.

This is a good practice to get into because it ensures that your cleanup code always executes. Of course using the Resoource Acquisition Is Initialization idiom is a much cleaner way of ensuring that resources get cleaned up, but I'm not versed enough in VB.net to know if this is possible to do.

like image 39
Nick Haddad Avatar answered Oct 04 '22 10:10

Nick Haddad


Finally should be used to everything that needs to be done in order to keep a system consistent. This usually means release resources

Finally is always executed, no matter what exception was thrown. It should be used to release resources, in the following cases:

  • Finalize a connection
  • Close a file handler
  • Free memory
  • Close a database connection

Let me give a complete example. Imagine that that you are sending messages through the network. In pseudo-code:

// With finally                  |  //Without finally
try{                             |  try{  
  send_message()                 |    send_message() 
} catch(NetworkError){           |  } catch(NetworkError){ 
  deal_with_exception()          |    deal_with_exception()
} finally {                      |  }
  finalizes_connection()         |  finalizes_connection() 
}                                |

The only difference of both codes is when what is hold in the try block raises an exception that is not NetworkError, for example, MethodNotFound. In the first case, the method finalizes_connection() will be called, and in the second one, it will not.

A connection is naturally done through more than one program. So what happens in the case of a MethodNotFound exception to the other program? In the first case, your program will finish the connection and the other program and it will be happy. In the second case, the other program can be waiting for your response forever. What if the other program can only receive one connection per time? You just bugged the other program as well.

This would also apply for a file, for example, that you opened and other programs wouldn't be able to open for reading (in Windows). And for memory, it is never released and now you have a memory leak.

like image 31
fotanus Avatar answered Oct 02 '22 10:10

fotanus


you use finally for cleanup code, eg db connections or files that are open that needs to be close. Virtually any cleanup code that needs to execute regardsless of an exception or not

also, your exception handling might require to re throw the exception, or other exception, in which case the code after the block will not be executed

like image 30
Adriaan Stander Avatar answered Oct 01 '22 10:10

Adriaan Stander


Doing clean up in a finally block is to ensure that it is run. If the catch block doesn't deal with the exception (ie. it just logs it), or even causes another exception, the code in the finally block will still run.

like image 38
adrianbanks Avatar answered Oct 02 '22 10:10

adrianbanks


On top of what everyone else said, semantically I think that they are different.

Code in the finally block clearly states that you're doing finalization type tasks for the content contained within the try-catch. I think this makes it clearer to read.

like image 23
Giovanni Galbo Avatar answered Oct 03 '22 10:10

Giovanni Galbo


As far as I can remember I have never used a try/catch/finally block in my .NET code.

In general, catching exceptions in the middle tier is rarely needed. Exceptions are usually propagated to a top-level handler in the presentation tier (and possibly caught and rethrown at a tier boundary so they can be logged).

So in the middle tier you will more often see try/finally (or the "using" statement) so that resources are cleaned up. And in try/catch in the top-level handler in the presentation tier.

In the rare cases that I need to both catch an exception and do some cleanup, I would prefer to refactor so that the following:

try
{
    ... do something
}
catch
{
   ... handle exception
}
finally
{
   ... cleanup
}

becomes:

try
{
    DoSomethingAndCleanup();
}
catch
{
   ... handle exception
}

...
private void DoSomethingAndCleanup()
{
    try
    {
        ... do something
    }
    finally
    {
        ... cleanup
    }
}

IMHO this is much cleaner.

like image 44
Joe Avatar answered Oct 04 '22 10:10

Joe