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");
}
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");
}
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.
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.
Yes, code in finally
block is guaranteed to get executed even if an exception is thrown within the try
block.