Intercepting an exception inside IDisposable.Dispose

前端 未结 11 1797
有刺的猬
有刺的猬 2020-12-13 02:07

In the IDisposable.Dispose method is there a way to figure out if an exception is being thrown?

using (MyWrapper wrapper = new MyWrapper())
{
           


        
11条回答
  •  醉梦人生
    2020-12-13 02:34

    This will catch exceptions thrown either directly or inside the dispose method:

    try
    {
        using (MyWrapper wrapper = new MyWrapper())
        {
            throw new MyException("Bad error.");
        }
    }
    catch ( MyException myex ) {
        //deal with your exception
    }
    catch ( Exception ex ) {
        //any other exception thrown by either
        //MyWrapper..ctor() or MyWrapper.Dispose()
    }
    

    But this is relying on them using this this code - it sounds like you want MyWrapper to do that instead.

    The using statement is just to make sure that Dispose always gets called. It's really doing this:

    MyWrapper wrapper;
    try
    {
        wrapper = new MyWrapper();
    }
    finally {
        if( wrapper != null )
            wrapper.Dispose();
    }
    

    It sounds like what you want is:

    MyWrapper wrapper;
    try
    {
        wrapper = new MyWrapper();
    }
    finally {
        try{
            if( wrapper != null )
                wrapper.Dispose();
        }
        catch {
            //only errors thrown by disposal
        }
    }
    

    I would suggest dealing with this in your implementation of Dispose - you should handle any issues during Disposal anyway.

    If you're tying up some resource where you need users of your API to free it in some way consider having a Close() method. Your dispose should call it too (if it hasn't been already) but users of your API could also call it themselves if they needed finer control.

提交回复
热议问题