Share via


Be careful about exception after resource allocation

The following is a common code pattern

        Resource resource = GetResource();

        DoWork();

        return resource;

If DoWork() throws exception, the resource will be leaked. We need to guard against this.

For example

        bool success = false;

        Resource resource = GetResource();

        try

        {

            DoWork();

            success = true;

            return resource;

        }

        finally

        {

            if (!success)

            {

                DisposeResource(resource);

            }

        }

Comments

  • Anonymous
    February 02, 2009
    PingBack from http://blog.a-foton.ru/index.php/2009/02/02/be-careful-about-exception-after-resource-allocation/

  • Anonymous
    February 02, 2009
    I use rethrowing for the same concept: Resource resource = GetResource(); try {    DoWork();    return resource; } catch {    DisposeResource(resource);    throw; } It saves having to fiddle with flags.

  • Anonymous
    February 04, 2009
    If the CLR designers had the foresight to actually enable programmers to implement RAII idiom, none of this would be a problem. VC++ had to retrofit the concept with VC2005 in C++/CLI. Your best bet is to do what you did or implement IDisposable.

  • Anonymous
    February 27, 2009
    I don't know how to contact you with a question I have. So here it is for you: I want to programatically (C#) Ngen then GAC to boost performance. I have a list of assemblies. How would I do this using your GAC wrapper? We support XP and V. Any code samples will truly go far to help us. Thanks, ~yamazed

  • Anonymous
    March 09, 2009
    @barrkel: Your solution is not at all equal to the finally pattern. Catching and re-throwing the exception will "destroy" the original exception stack and the next catch (or WER) will not get the correct context.

  • Anonymous
    April 23, 2009
    The comment has been removed