Finally, a block in C #

Possible duplicate:
Finally, the block does not work

I have a question about the final block in C #. I wrote a small code example:

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 know, finally, a block, suppose, should work deterministically, regardless of whether an exception was thrown. Now, if the user enters "Y" - a NullReferenceException is thrown, execution proceeds to the catch clock and then to the finally block, as I expected. But if the input is something else, an ArgumentException is thrown. There is no suitable catch block to catch this exception, so I thought that execution should move the finally block, but it is not. Can someone explain to me why?

thanks everyone :)

+5
2

, , ArgumentException, , "" . ( JIT), finally.

JIT, > > a >

, Visual Studio a > ( CTRL + F5)

Console.ReadLine() , finally.

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

, :


Throw NullReferenceException? N

: System.ArgumentException: .

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

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

, .,.

+6

, , .

:

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

foo() , .

try/catch .

+1

All Articles