Search code examples
c#unhandled-exceptionfinally

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.


Solution

  • 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.