Search code examples
c#.netexceptionusingusing-statement

Using statement doesn't work correctly


My class named S looks like that:

public class S : IDisposable
{
    public void Dispose()
    {
        // some code
    }

    public void f()
    {
        throw new Exception("exception");
    }
}

When I use using statement, f() method doesn't call s.Dispose() method. I thought it should call Dispose method even if the exception occurs. That's what I read in MSDN: "The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object". Am I missing something?

using (S s = new S())
{
    s.f();
}

Calling s.f() ends my program without disposing of my object s. I think I don't have to use try/catch, because using statement should do it for me.


Solution

  • The problem might be that you are running the code in the debugger. That means that whatever code comes after an unhandled exception wont be executed becuase the debugger will halt at that point.

    If you run a test scenario out of the debugger then the Dispose() method will be called when the runtime cleans up the mess. Put some code "marker" in the Dispose() method that will give you a visible sign that Dipose is called: for example create a file in some accessible folder namesd DisposedHasRun.yeah (note that outputting to the Console or a MessageBox is not an option because the application is quitting due to an unhandled exception). When you run the test case outside the debugger you'll see that the file has been created.

    That said, there are ocassions where Dispose wont be called (nor finally blocks). For example an StackOverflow exception due to an infinite recursion will not call Dispose() as the runtime will make the application bail out asap. (ThreadAbortException I think will behave the same)