Why use finally in C#?

C#Exception Handling

C# Problem Overview


Whatever is inside finally blocks is executed (almost) always, so what's the difference between enclosing code into it or leaving it unclosed?

C# Solutions


Solution 1 - C#

The code inside a finally block will get executed regardless of whether or not there is an exception. This comes in very handy when it comes to certain housekeeping functions you need to always run like closing connections.

Now, I'm guessing your question is why you should do this:

try
{
    doSomething();
}
catch
{
    catchSomething();
}
finally
{
    alwaysDoThis();
}

When you can do this:

try
{
    doSomething();
}
catch
{
    catchSomething();
}

alwaysDoThis();

The answer is that a lot of times the code inside your catch statement will either rethrow an exception or break out of the current function. With the latter code, the "alwaysDoThis();" call won't execute if the code inside the catch statement issues a return or throws a new exception.

Solution 2 - C#

Most advantages of using try-finally have already been pointed out, but I thought I'd add this one:

try
{
    // Code here that might throw an exception...
 
    if (arbitraryCondition)
    {
        return true;
    }
 
    // Code here that might throw an exception...
}
finally
{
    // Code here gets executed regardless of whether "return true;" was called within the try block (i.e. regardless of the value of arbitraryCondition).
}

This behaviour makes it very useful in various situations, particularly when you need to perform cleanup (dispose resources), though a using block is often better in this case.

Solution 3 - C#

any time you use unmanaged code requests like stream readers, db requests, etc; and you want to catch the exception then use try catch finally and close the stream, data reader, etc. in the finally, if you don't when it errors the connection doesn't get closed, this is really bad with db requests

 SqlConnection myConn = new SqlConnection("Connectionstring");
        try
        {
            myConn.Open();
            //make na DB Request                
        }
        catch (Exception DBException)
        {
            //do somehting with exception
        }
        finally
        {
           myConn.Close();
           myConn.Dispose();
        }

if you don't want to catch the error then use

 using (SqlConnection myConn = new SqlConnection("Connectionstring"))
        {
            myConn.Open();
            //make na DB Request
            myConn.Close();
        }

and the connection object will be disposed of automatically if there is an error, but you don't capture the error

Solution 4 - C#

Because finally will get executed even if you do not handle an exception in a catch block.

Solution 5 - C#

Finally statements can execute even after return.

private int myfun()
{
    int a = 100; //any number
    int b = 0;
    try
    {
        a = (5 / b);
        return a;
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
        return a;
    }

 //   Response.Write("Statement after return before finally");  -->this will give error "Syntax error, 'try' expected"
    finally
    {
      Response.Write("Statement after return in finally"); // --> This will execute , even after having return code above
    } 
    
    Response.Write("Statement after return after finally");  // -->Unreachable code
}

Solution 6 - C#

finally, as in:

try {
  // do something risky
} catch (Exception ex) {
  // handle an exception
} finally {
  // do any required cleanup
}

is a guaranteed opportunity to execute code after your try..catch block, regardless of whether or not your try block threw an exception.

That makes it perfect for things like releasing resources, db connections, file handles, etc.

Solution 7 - C#

i will explain the use of finally with a file reader exception Example

  • with out using finally

> try{ >
> StreamReader strReader = new StreamReader(@"C:\Ariven\Project\Data.txt"); > Console.WriteLine(strReader.ReadeToEnd()); > StreamReader.Close(); > } > catch (Exception ex) > { > Console.WriteLine(ex.Message); > }

in the above example if the file called Data.txt is missing, an exception will be thrown and will be handled but the statement called StreamReader.Close(); will never be executed.
Because of this resources associated with reader was never released.

  • To solve the above issue, we use finally

> StreamReader strReader = null; > try{ > strReader = new StreamReader(@"C:\Ariven\Project\Data.txt"); > Console.WriteLine(strReader.ReadeToEnd()); > } > catch (Exception ex){ > Console.WriteLine(ex.Message); > } > finally{ > if (strReader != null){ > StreamReader.Close(); > } > }

Happy Coding :)

Note: "@" is used to create a verbatim string, to avoid error of "Unrecognized escape sequence". The @ symbol means to read that string literally, and don't interpret control characters otherwise.

Solution 8 - C#

Say you need to set the cursor back to the default pointer instead of a waiting (hourglass) cursor. If an exception is thrown before setting the cursor, and doesn't outright crash the app, you could be left with a confusing cursor.

Solution 9 - C#

The finally block is valuable for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception. Control is always passed to the finally block regardless of how the try block exits.

Solution 10 - C#

Sometimes you don't want to handle an exception (no catch block), but you want some cleanup code to execute.

For example:

try
{
    // exception (or not)
}
finally
{
    // clean up always
}

Solution 11 - C#

Ahh...I think I see what you're saying! Took me a sec...you're wondering "why place it in the finally block instead of after the finally block and completely outside the try-catch-finally".

As an example, it might be because you are halting execution if you throw an error, but you still want to clean up resources, such as open files, database connections, etc.

Solution 12 - C#

Control Flow of the Finally Block is either after the Try or Catch block.

[1. First Code]
[2. Try]
[3. Catch]
[4. Finally]
[5. After Code]

with Exception 1 > 2 > 3 > 4 > 5 if 3 has a Return statement 1 > 2 > 3 > 4

without Exception 1 > 2 > 4 > 5 if 2 has a return statement 1 > 2 > 4

Solution 13 - C#

As mentioned in the documentation:

> A common usage of catch and finally together is to obtain and use resources in a try block, deal with exceptional circumstances in a catch block, and release the resources in the finally block.

It is also worth reading this, which states:

> Once a matching catch clause is found, the system prepares to transfer control to the first statement of the catch clause. Before execution of the catch clause begins, the system first executes, in order, any finally clauses that were associated with try statements more nested that than the one that caught the exception.

So it is clear that code which resides in a finally clause will be executed even if a prior catch clause had a return statement.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRodrigoView Question on Stackoverflow
Solution 1 - C#Kevin PangView Answer on Stackoverflow
Solution 2 - C#NoldorinView Answer on Stackoverflow
Solution 3 - C#Bob The JanitorView Answer on Stackoverflow
Solution 4 - C#Matt BriggsView Answer on Stackoverflow
Solution 5 - C#Prateek GuptaView Answer on Stackoverflow
Solution 6 - C#David AlpertView Answer on Stackoverflow
Solution 7 - C#Ariven NadarView Answer on Stackoverflow
Solution 8 - C#Chris DoggettView Answer on Stackoverflow
Solution 9 - C#cgreenoView Answer on Stackoverflow
Solution 10 - C#markomView Answer on Stackoverflow
Solution 11 - C#BeskaView Answer on Stackoverflow
Solution 12 - C#Ranald FongView Answer on Stackoverflow
Solution 13 - C#NexaspxView Answer on Stackoverflow