I have read that a using like this:
using (myObject)
{
myObject.DoStuff();
}
Can be thought of like this:
try
{
myObject.DoStuff();
}
finally
{
myobject.Dispose()
}
So if myObejct.DoStuff throws ExceptionA
and then myObject.Dispose() also throws an exception (ExceptionB) then ExceptionA
will be lost. (See the MSDN examples here for a better description.)
Does this mean that if the code inside a using block code could throw an exception (which is most code right?) then a using
statement is a bad practice?
Does this mean that if the code inside a using block code could throw an exception (which is most code right?) then a using statement is a bad practice?
No.
and then myObject.Dispose() also throws an exception
This is really the crux of your question.
This is the "bad practice" here. IDisposable.Dispose
implementations should really be designed so that they don't raise exceptions except in situations which are truly unrecoverable.
Since IDisposable
is really intended to release the resource in question, the main issue should be making sure that this implementation won't throw under most circumstances. Having a cleanup method throw will cause a lot of grief - and is the reason why the using statement shouldn't be used with WCF clients, etc.
That being said, I don't think the using statement itself is a bad practice. In fact, it tends to be a very good practice, as it avoids a very common pitfall (missing the disposable of a resource in the case of an exception).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With