Whatever is inside finally blocks is executed (almost) always, so what's the difference between enclosing code into it or leaving it unclosed?
-
3What do you mean by leaving it unclosed? – Ramesh Feb 13 '09 at 21:37
-
5And what do you mean by "(almost)"? – Beska Feb 13 '09 at 21:38
-
1That is not true at all. The whole point is that if an error occurs, control will jump to the catch block. The only way it would always run all of the code is if no exception ever occurred, and then why would you use the try/catch at all? – Ed S. Feb 13 '09 at 21:42
-
52If you pull the power cord out while a machine is executing a try clause the finally clause will not be called. – Dour High Arch Feb 13 '09 at 21:43
-
3@Ed: Use transactions. Your try clause has to make some kind of temporary or in-memory change that can be persisted in a single, atomic, change in the finally clause. This is rarely easy and may require special hardware. – Dour High Arch Feb 13 '09 at 22:10
-
Not really C+, but as this question applies to all languages here a good real-world example from PHP using MySqli: https://wiki.php.net/rfc/finally – rugk Jan 23 '17 at 14:02
-
1Try-catch-Finally may have originated in C (I say "may have" only because I don't know if there is an older language that has it or not), but it has made its way into JAVA, Python (as "Try-Except-Finally") and probably other languages as well. I recommend adding tags for other languages on this question. It helped me understand something in Python. Thanks for posting. – TMWP Apr 21 '17 at 17:57
13 Answers
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.

- 41,172
- 38
- 121
- 173
-
52
-
6in fact, it applies even without a catch{} block (just try/finally, letting exceptions bubble up) – Lucas Feb 13 '09 at 21:49
-
Very good. You could also use `using` block to create and dispose of resources rather than `finally`, and have a try catch block(s) inside the statement (`using` does NOT replace `try catch`). The only advantage of this is that you dispose of the resource as soon as you leave the block (which you may or may not remember to do with `finally`), but I'm sure there are many cases where you'd probably want to use `finally` instead. See http://stackoverflow.com/a/248984/201648 – Aaron Newton Sep 27 '12 at 12:09
-
Finally block still doesn't get executed if there is an exception in the catch block. – Suyash Gupta Feb 08 '19 at 10:54
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.

- 144,213
- 56
- 264
- 302
Because finally will get executed even if you do not handle an exception in a catch block.

- 41,224
- 16
- 95
- 126
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

- 20,292
- 10
- 49
- 72
-
2Dispose() will also Close() the connection, no need to call both. Close() does NOT Dipose(), you can reopen the connection. – Lucas Feb 13 '09 at 23:05
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
}

- 880
- 1
- 10
- 21
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.

- 3,770
- 3
- 25
- 37

- 3,161
- 1
- 23
- 19
-
3All of those examples are typically better served with a using block, but that doesn't really detract from your answer. – Joel Coehoorn Feb 13 '09 at 21:43
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.

- 1,278
- 13
- 13
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.

- 19,959
- 4
- 61
- 86
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.

- 31,943
- 7
- 66
- 87
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
}

- 2,040
- 1
- 21
- 29
-
If the exception is not caught, execution of the finally block depends on whether the operating system chooses to trigger an exception unwind operation. – Vikas Verma Sep 22 '14 at 18:18
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

- 401
- 3
- 12
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.

- 12,445
- 14
- 77
- 112
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.

- 371
- 4
- 20