Question

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 :)

Was it helpful?

Solution

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.

class Program {
    static void Main(string[] args) {
        MyType t = new MyType();
        t.foo();
        Console.ReadLine();
    }
}

Here is the output you should get:


Throw NullReferenceException? N

Unhandled Exception: System.ArgumentException: Value does not fall within the ex pected range.

at ConsoleSandbox.MyType.foo() in P:\Documents\Sandbox\Console\Console\Consol e\Program.cs:line 17

at ConsoleSandbox.Program.Main(String[] args) in P:\Documents\Sandbox\Console \Console\Console\Program.cs:line 31

finally block

Press any key to continue . . .

OTHER TIPS

What you see is an artifact of your test program.

If you change your main method:

 static void Main(string[] args)
 {
    try
    {
        MyType t = new MyType();
        t.foo();
    }
    catch
    {
       // write something
    }
 }

Then your foo() will behave as expected.

Without that toplevel try/catch, your entire program was being aborted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top