开发者

Why isn't the finally executed in this situation?

I have the following code:

class SampleClass : IDisposable
{

    public void Dispose()
    {
        Console.WriteLine("Execute Dispose!");
    }
}

static void Main(string[] args)
{
    SampleClass sc = new SampleClass();

    try
    {
        throw new 开发者_如何学编程Exception();
    }
    finally
    {
        sc.Dispose();
    }
}

However when I run this it doesn't print the Execute Dispose! message, why is this?

UPDATE:

If I changed the code like so:

static void Main(string[] args)
{
    SampleClass sc = new SampleClass();

    try
    {
        try
        {
            throw new Exception();
        }
        finally
        {
            sc.Dispose();
        }
    }
    catch
    {
        throw;
    }
}

It prints the message first and then crashes.

What I thinking about is If the app crash at first can it be disposed as well as you like?

I know it is simple, But I really what to learn more.


You have an unhandled exception. Program behaviour is implementation-dependent when you have an unhandled exception.

As you have discovered, in your particular implementation an unhandled exception first asks you if you want to debug the unhandled exception (or prints the exception out on the console), and then runs the finally block.

Note that it is not guaranteed that the finally block runs when there is an unhandled exception. The implementation is allowed to terminate the process immediately upon an unhandled exception if it sees fit to do so.

If you don't like that behaviour then your choices are to either prevent or handle the exception, or get a different implementation of the runtime that does something you like better.


It does print Execute Dispose! on the window. You should look closer.


It gets executed in my test(LinqPad).

As a normal console app the message comes after the exception message.

Unhandled Exception: System.Exception: Exception of type 'System.Exception' was thrown.
at OutputTest.Program.Main(String[] args) in D:...\Program .cs:line 27
Execute Dispose!
Press any key to continue . . .

But it only shows once you closed the "App has stopped working window"


It does get printed. Maybe the exception saying "Application has stopped working" is preventing you from seeing it. Click cancel and see the printed message.

Screenshot:

Why isn't the finally executed in this situation?


Like others have said, the code does work. You might want to use the using constructor though (you can use that if the class implements IDisposable)

class SampleClass : IDisposable {
    public void Dispose() {
        Console.WriteLine("Execute Dispose!");
    }
}

static void Main(string[] args) { 
    using (SampleClass sc = new SampleClass()) {
        throw new Exception();
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜