Search code examples
c#exceptiontry-catchdispose

How to dispose an object only when an exception was raised?


I instantiate a disposable object (in my case a FileStream) in my constructor and need to do some work on it. However, this might throw any number of different exceptions. Now I don't even want to mess with these exceptions too much and want to allow them to propagate up to the caller. However, I need to dispose the object first. Now what's the best way to do that? Right now I can only think of something like that:

IDisposable disposableObject = InstantiateDisposable();
bool error = false;
try
{
    DoWork(disposableObject);
}
catch (ReallyBadException e)
{
    error = true;
    throw new EvenWorseException("some message", e);
}
catch (Exception)
{
    error = true;
    throw;
}
finally
{
    if (error) disposableObject.Dispose();
}

Is that even correct or will the Dispose() be skipped in some special cases? Is there an easier way to do that? It gets a bit cumbersome, if you need to catch a bunch of different exceptions seperately for whatever reason and you always have to copy & paste that error = true; bit.

Edit: Just to clarify: I only need to dispose the object in case of DoWork() failing / throwing an exception. If this method succeeds, I don't want to dispose the object just yet, as there'll be more work to do with it later on.


Solution

  • Why not invert the logic?

    IDisposable disposableObject = InstantiateDisposable();
    bool error = true;
    try
    {
        DoWork(disposableObject);
        error = false; // if it gets to this line, no exception was thrown
    }
    catch (ReallyBadException e)
    {        
        throw new EvenWorseException("some message", e);
    }    
    finally
    {
        if (error) disposableObject.Dispose();
    }