0

Possible Duplicate:
try catch finally question

if an exception is not caught, does the code statements are executed

try
{
  throw new Exception("test example");    
}

finally
{
  Console.WriteLine("finally block"); 
}
Community
  • 1
  • 1
Raghav
  • 1

4 Answers4

6

Yes, finally blocks run regardless of exception*.

Please see try-finally (C# Reference):

The finally block is useful 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.

* Note that this is not entirely true. Some exceptions, like a StackOverflowException will terminate the process immediately. But for the sake of this discussion it is fairly safe to say that a finally block will always run.

Andrew Hare
  • 344,730
  • 71
  • 640
  • 635
2

Yes. Finally blocks are always executed.

porges
  • 30,133
  • 4
  • 83
  • 114
2

The only time when code in the finally block is not executed is when the power fails or the computer crashes before execution reaches it.

See http://thedailywtf.com/Articles/My-Tales.aspx

Chris Wenham
  • 23,679
  • 13
  • 59
  • 69
0

Yes, code in finally block is guaranteed to get executed even if an exception is thrown within the try block.

Florian Greinacher
  • 14,478
  • 1
  • 35
  • 53