Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle exceptions thrown by disposable objects?

Tags:

c#

idisposable

What is the best way for using Disposable objects, assuming Constructor and Process methods may throw exception? I generally prefer one of below implementations.

  1. try-catch surrounding using block

    try
    {
        using (Disposable dispObj = new Disposable())
        {
            dispObj.Process();
        }
    }
    catch (Exception ex)
    {
        // Do something
    }
    
  2. 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.

like image 488
Mehmet Ataş Avatar asked Aug 01 '12 09:08

Mehmet Ataş


2 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();
}
like image 180
Nikhil Agrawal Avatar answered Sep 28 '22 08:09

Nikhil Agrawal


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.

like image 31
Anders Arpi Avatar answered Sep 28 '22 08:09

Anders Arpi