Another interview question which was expecting a true / false answer and I wasn't too sure.
-
2reminds me of http://thedailywtf.com/Articles/My-Tales.aspx – Russ Cam May 07 '09 at 10:48
-
This is exact duplicate... I wonder why it's not closed yet. – Mehrdad Afshari May 07 '09 at 11:00
-
If one used catch to catch X and do stuff, whats left for finally to do ? – mP. May 07 '09 at 11:14
-
@mP: cleaning up the mess, if needed :) – leppie May 07 '09 at 11:16
-
Undeleted via http://meta.stackexchange.com/questions/97222/no-longer-dupe-requires-reopening Please read discussion and contribute before deleting this or any of the related dupes. Thx. – John K Jul 02 '11 at 15:35
-
Gais, are you able to mark an Accepted Solution? – John K Jul 02 '11 at 15:35
9 Answers
finally
is executed most of the time. It's almost all cases. For instance, if an async exception (like StackOverflowException
, OutOfMemoryException
, ThreadAbortException
) is thrown on the thread, finally
execution is not guaranteed. This is why constrained execution regions exist for writing highly reliable code.
For interview purposes, I expect the answer to this question to be false (I won't guarantee anything! The interviewer might not know this herself!).

- 414,610
- 91
- 852
- 789
-
Very interesting, never heard of CERs before. Thanks for raising it here. – Colin Desmond May 07 '09 at 11:05
-
1+1 This is an often-missed and very important point! It is dangerous to say that "finally" **always** executes for the reasons you point out. Nice answer. – Andrew Hare May 07 '09 at 11:10
-
1Completely agreed. I think the source of the problem is MSDN itself. It should increase awareness of this fact in links such as the one mentioned in the accepted answer. When MSDN itself says.. "finally is used to guarantee a statement block of code executes regardless of how the preceding try block is exited" which is wrong, this will be the result. I know *very few* people who don't answer yes to this question. – Mehrdad Afshari May 07 '09 at 11:18
-
I see someones been doing their homework, great answer! A very interesting article too. – John T May 07 '09 at 11:20
-
-
@Jonathan: It does solve issues with OutOfMemoryExceptions by preparing the method beforehand. Read the linked article. – Mehrdad Afshari May 07 '09 at 11:53
-
7Also don't forget the much more common cases where it doesn't execute because the power went out, the hardware malfunctioned, the OS killed the process, etc. If you've half-finished writing a sensitive file and the OS kills you, the finally block won't save you. – Craig Gidney May 08 '09 at 21:21
Straight from MSDN:
The finally block is useful for cleaning up any resources allocated in the try block. Control is always passed to the finally block regardless of how the try block exits.
Whereas catch is used to handle exceptions that occur in a statement block, finally is used to guarantee a statement block of code executes regardless of how the preceding try block is exited.
http://msdn.microsoft.com/en-us/library/zwc8s4fz(VS.71,loband).aspx

- 105,982
- 98
- 297
- 360

- 23,735
- 11
- 56
- 82
-
1
-
-
2Not always true... MSDN is not always truth. Also from MSDN: http://msdn.microsoft.com/en-us/magazine/cc163716.aspx http://msdn.microsoft.com/en-us/library/ms228973.aspx For the purpose of an interview question, I'd expect "No" as the answer. – Mehrdad Afshari May 07 '09 at 11:19
Generally the finally
block is guaranteed to execute.
However, a few cases forces the CLR to shutdown in case of an error. In those cases, the finally
block is not run.
One such example is in the presence of a StackOverflow exception.
E.g. in the code below the finally
block is not executed.
static void Main(string[] args) {
try {
Foo(1);
} catch {
Console.WriteLine("catch");
} finally {
Console.WriteLine("finally");
}
}
public static int Foo(int i) {
return Foo(i + 1);
}
The other case I am aware of is if a finalizer throws an exception. In that case the process is terminated immediately as well, and thus the guarantee doesn't apply.
The code below illustrates the problem
static void Main(string[] args) {
try {
DisposableType d = new DisposableType();
d.Dispose();
d = null;
GC.Collect();
GC.WaitForPendingFinalizers();
} catch {
Console.WriteLine("catch");
} finally {
Console.WriteLine("finally");
}
}
public class DisposableType : IDisposable {
public void Dispose() {
}
~DisposableType() {
throw new NotImplementedException();
}
}
In both cases the process terminates before both catch
and finally
.
I'll admit that the examples are very contrived, but they are just made to illustrate the point.
Fortunately neither happens very often.

- 114,645
- 34
- 221
- 317
-
Interesting point, but it should probably be noted that the second example doesn’t catch the exception because it occurred on a different/unprotected thread. – Matthew Whited Jan 21 '10 at 20:08
It is not totally true that finally will always be executed. See this answer from Haacked:
Two possibilities:
StackOverflowException
ExecutingEngineException
The finally block will not be executed when there's a StackOverflowException since there's no room on the stack to even execute any more code. It will also not be called when there's an ExecutingEngineException, which is very rare.
However, these two exceptions are exception you cannot recover from, so basically your process will exit anyway.
As mentioned by Mehrdad, a reliable try/catch/finally will have to use Constrained Execution Regions (CER). An example is provided by MSDN:
[StructLayout(LayoutKind.Sequential)]
struct MyStruct
{
public IntPtr m_outputHandle;
}
sealed class MySafeHandle : SafeHandle
{
// Called by P/Invoke when returning SafeHandles
public MySafeHandle()
: base(IntPtr.Zero, true)
{
}
public MySafeHandle AllocateHandle()
{
// Allocate SafeHandle first to avoid failure later.
MySafeHandle sh = new MySafeHandle();
RuntimeHelpers.PrepareConstrainedRegions();
try { }
finally
{
MyStruct myStruct = new MyStruct();
NativeAllocateHandle(ref myStruct);
sh.SetHandle(myStruct.m_outputHandle);
}
return sh;
}
}

- 1
- 1

- 172,527
- 53
- 255
- 316
Generally the finally block is always executed regardless of whether an exception is thrown or not and whether any exception is handled or not.
There are a couple of exceptions (see other answers for more details).

- 134,786
- 31
- 255
- 325
'Finally' is executed regardless of whether an exception is thrown or not.
Its a good place to close any open connections. Successful or failed execution, you can still manage your connections or open files.

- 2,780
- 4
- 33
- 37
Finally is always executed. I not depends on how the try block works. If u have to do some extra work for both try and cath, it is better to put in finally block. So you can gurantee that it is always executed.

- 16,668
- 41
- 122
- 174