Possible Duplicate:
Finally Block Not Running??
I have a question regarding finally block in c#.
I wrote a small sample code:
public class MyType
{
public void foo()
{
try
{
Console.WriteLine("Throw NullReferenceException?");
string s = Console.ReadLine();
if (s == "Y")
throw new NullReferenceException();
else
throw new ArgumentException();
}
catch (NullReferenceException)
{
Console.WriteLine("NullReferenceException was caught!");
}
finally
{
Console.WriteLine("finally block");
}
}
}
class Program
{
static void Main(string[] args)
{
MyType t = new MyType();
t.foo();
}
}
As I far as I know, finally block suppose to run deterministicly, whether or not an exception was thrown.
Now, if the user enters “Y” – NullReferenceException is thrown, execution moves to the catch clock and then to the finally block as I expected.
But if the input is something else – ArgumentException is thrown. There is no suitable catch block to catch this exception, so I thought execution should move the the finally block – but it doesnt. Could someone please explain me why?
thanks everyone 🙂
Your debugger is probably catching the ArgumentException so it’s waiting for you to “handle” it there before entering the final block. Run your code w/o an attached debugger (including w/o your JIT debugger) and it should hit your finally block.
To disable JIT, go to Options > Tools > Debugging > Just-In-Time and uncheck Managed
To debug w/o an attached debugger, in Visual Studio go to Debug > Start Without Debugging (or CTRL + F5)
It would also be helpful to put a Console.ReadLine() at the end of your program to prevent the console from closing after entering your finally block.
Here is the output you should get: