8

What is the difference between 2 conditions? Every time when method1 or method2 runs, there should be a code block that is required to run. It seems to me that 2 method are the same.

// example method1
void Method1(void)
{
    try
    {
        // do something
    }
    catch (Exception ex)
    {
        // do something
    }
    finally
    {
        // do something whenever method1 runs
    }
}

// example method2
void Method2(void)
{
    try
    {
        // do something
    }
    catch (Exception ex)
    {
        // do something
    }

    // do something whenever method2 runs
}

Finally block seems to be unnecessary for me.

sanchop22
  • 2,729
  • 12
  • 43
  • 66
  • 1
    You need to be concrete about the `do something`s to make this a question. – H H Mar 15 '12 at 09:43
  • depends on what 'do something' does – StaWho Mar 15 '12 at 09:44
  • Your exception in Method2 would mean you might not ever get to the end of the method. In Method 1 finally will always run. Not posted as an answer because I will leave someone else to give examples etc. – AnthonyBlake Mar 15 '12 at 09:44
  • No, they are not the same. A `finally` block ensures that the code it contains runs, regardless of what else happens. – Cody Gray - on strike Mar 15 '12 at 09:51
  • 3
    don't catch what you can't handle – Jodrell Mar 15 '12 at 09:56
  • Please read the following for more info. Finally is optional where you could release resources after all processing is done. http://msdn.microsoft.com/en-us/library/fk6t46tz(v=vs.71).aspx – Kaf Mar 15 '12 at 09:44
  • VB.NET question but pretty much the same: https://stackoverflow.com/questions/1158667/why-use-finally-in-try-catch – nawfal Oct 01 '21 at 12:55

7 Answers7

17

In your first example, you could re-throw the exception and the code inside the finally would still run. This would not be possible in the second example.

If you choose not to re-throw the exception, then yes there is little difference. However, this is considered bad form - very rarely should you need to consume an exception that you cannot explicitly handle.

It is a keyword to help you with code execution flow. When you throw an exception the execution flow of the code is affected (like using return), the finally keyword allows you to express that when an exception occurs (or you return from a try) you still want execution to do something as it's leaving.

To answer the question facetiously, it is a must when you need it and not when you don't.


Further Reading

To be on the safe side, before you attempt to start making use of this keyword, please read the documentation for it:

http://msdn.microsoft.com/en-us/library/zwc8s4fz.aspx

And the exception handling keywords in general:

http://msdn.microsoft.com/en-us/library/s7fekhdy.aspx


Examples

Catch an exception to do something with it, then re-throw it. Use finally to call any tidy-up code:

try
{
    OpenConnectionToDatabase();
    // something likely to fail
}
catch (Exception ex)
{
    Log(ex);
    throw;  
    // throw ex; // also works but behaves differently
}
// Not specifying an exception parameter also works, but you don't get exception details.
//catch (Exception)
//{
//    Log("Something went wrong);
//    throw;
//}
finally
{
    CloseConnectionToDatabase();
}

Don't register any interest in catching exceptions, but use finally to tidy-up code:

try
{
    OpenConnectionToDatabase();
    // something likely to fail
}
finally
{
    CloseConnectionToDatabase();
}

Return from your try because it looks nicely formatted, but still use finally to tidy-up code:

try
{
    OpenConnectionToDatabase();
    return 42;
}
finally
{
    CloseConnectionToDatabase();
}
Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
  • Well, yes and no. I have a ton of catch(rethrow scenarios in base classes - that call a logging interface to write the exception to the application log. Even IF handled further up I want to know stuff like database exceptions all the time. – TomTom Mar 15 '12 at 09:47
  • 1
    @TomTom They are not consumed, they are observed then propagated. By consumed I mean swallowed never to be seen again. – Adam Houldsworth Mar 15 '12 at 09:50
  • @AdamHouldsworth he is clearly aware of what finally does but doesn't understand why he would need it. I think it would help him. Far more than "reading the spec". – AnthonyBlake Mar 15 '12 at 11:02
  • @AdamHouldsworth Sorry for suggesting how you could improve your answer. I am trying to help people. I see you deleted the comment in question. Sorry I didn't mean to touch a nerve. – AnthonyBlake Mar 15 '12 at 11:25
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/8914/discussion-between-anthonyblake-and-adam-houldsworth) – AnthonyBlake Mar 15 '12 at 11:34
3

As you know the code written inside the finally block always runs. Please have a look onto the following point written below, it will clear your all confusion.

  1. Finally is used for Resource management. Mainly for releasing an resources. It always runs independent upon the Exception.
    1. As we know catch is used for handle an exception, but sometimes it fails to handle to an External exception. Then the finally block is used to handle that exception to perform the operation.
Sonu
  • 458
  • 5
  • 13
2

The code in the finally block will run anyway after the try-catch, it is very usefull for clean up.

try
{
    // open resources
}
catch (Exception ex)
{
    // something bad happened
}
finally
{
    // close resources that are still opened
}
MByD
  • 135,866
  • 28
  • 264
  • 277
1

This will behave very differently depending on whether you return from the try, for example. Also - the finally will run even if the catch throws an exception (or re-throws the original exception), which will not happen without the finally.

So: it isn't required, but it will behave differently. So if you want the code to happen, put it in the finally.

In many ways, try/finally is much more common than try/catch or try/catch/finally.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

You do not absolutely have to have the finally block, however, having it guarantees that the code within it will always run (unless there is an exception in the finally!).

Consider the following:

void Method2(void) 
{ 
    try 
    { 
        // do something 
    } 
    catch (Exception ex) 
    { 
        // do something 
        throw;
    } 

    // do something whenever method2 runs 
} 

the code after the try/catch will not execute if an exception is thrown. Additionally, if the code within the catch block has an error that causes an exception (such as your logging throwing an unexpected exception) the code that should have been in the finally will not run, leaving and cleanup undone.

Also a return statement will cause that code to not be run, while the finally will still be executed (also, here you can see that the catch can be skipped too, allowing any exceptions to propogate upwards - AFTER executing the finally):

void Method2(void) 
{ 
    try 
    {  
        // do something
        return
    } 
    finally
    {     
        // do something whenever method2 runs 
    }
} 

Whenever you have cleanup code that must be run at the end of a method, use finally (or if your objects implement IDisposable use the using statement).

David Hall
  • 32,624
  • 10
  • 90
  • 127
0

The finally block ensures that any code within it ALWAYS gets executed so if you have a return statement inside your try block or rethrow an exception within your catch block, the code inside the finally block will always execute.

It is a must if you need to ensure that something happens regardless (e.g. disposing of a resource etc)

Trevor Pilley
  • 16,156
  • 5
  • 44
  • 60
0

The big difference is that try...catch will swallow the exception, hiding the fact that an error occurred. try..finally will run your cleanup code and then the exception will keep going, to be handled by something that knows what to do with it.