Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are "using" statements "bad code"? [closed]

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?

like image 485
Vaccano Avatar asked Nov 28 '22 03:11

Vaccano


1 Answers

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).

like image 170
Reed Copsey Avatar answered Dec 13 '22 18:12

Reed Copsey