What is the best way for using Disposable objects, assuming Constructor and Process methods may throw exception? I generally prefer one of below implementations.
try-catch surrounding using block
try
{
using (Disposable dispObj = new Disposable())
{
dispObj.Process();
}
}
catch (Exception ex)
{
// Do something
}
try-catch-finally block.
Disposable dispObj2 = null;
try
{
dispObj2 = new Disposable();
dispObj2.Process();
}
catch (Exception ex)
{
// Do something
}
finally
{
if (dispObj2 != null)
{
dispObj2.Dispose();
}
}
UPDATE:
Again: "assuming Constuctor and Process methods may throw exception". I really do not understand why did nobody care about exceptions in their answers.
using
is good. It has an inbuilt try-finally block. If exception occurs, dispose method is called automatically.
This is fine
using (Disposable dispObj = new Disposable())
{
dispObj.Process();
}
Do it like this:
using (Disposable dispObj = new Disposable())
{
dispObj.Process();
}
Disposable objects are always disposed when they go out of scope of the using
clause, even if it's by an exception.
And don't use an empty catch {}
, completely pointless.
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