sanchop22
sanchop22

Reputation: 2809

Is finally block in C# a must?

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.

Upvotes: 8

Views: 2582

Answers (7)

Sonu
Sonu

Reputation: 458

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.

Upvotes: 3

Adam Houldsworth
Adam Houldsworth

Reputation: 64517

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();
}

Upvotes: 17

David Hall
David Hall

Reputation: 33173

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).

Upvotes: 1

user1082916
user1082916

Reputation:

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.

Upvotes: 0

Trevor Pilley
Trevor Pilley

Reputation: 16413

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)

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063774

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.

Upvotes: 1

MByD
MByD

Reputation: 137392

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
}

Upvotes: 2

Related Questions