How do you catch exceptions with "using" in C#

using isn't designed to catch exceptions; it's designed to give you an easy way to wrap a try/finally around an object that needs to be disposed. If you need to catch and handle exceptions then you'll need to expand it into a full try/catch/finally or put a containing try/catch around the whole thing.


To answer your edit (is using a replacement for try/catch/finally?) then no, it isn't. Most of the time when using a disposable resource you aren't going to handle the exception there and then because there's normally nothing useful you can do. So it provides a convenient way to just ensure that the resource is cleaned up irrespective of what you're trying to do works or not.

Typically code that deals with disposable resources is working at too low a level to decide what the correct action is on failure, so the exception is left to propagate to the caller who can decide what action to take (e.g. retry, fail, log, etc.). The only place where you'd tend to use a catch block with a disposable resource is if you're going to translate the exception (which is, I assume, what your data access layer is doing).


using (var cmd = new SqlCommand("SELECT * FROM Customers"))
{
    cmd.CommandTimeout = 60000;
    ...
}

is syntactic sugar for

var cmd = new SqlCommand("SELECT * FROM Customers");
try
{
    cmd.CommandTimeout = 60000;
    ...
}
finally
{
    if (cmd != null)
        cmd.Dispose();
}

So when people are telling you that "using" is a replacement for try/catch/finally they are implying that you should use the long-hand form but add in your catch block:

var cmd = new SqlCommand("SELECT * FROM Customers");
try
{
    cmd.CommandTimeout = 60000;
    ...
}
catch (Exception ex)
{
    ...//your stuff here
}
finally
{
    if (cmd != null)
        cmd.Dispose();
}

Wrap all the using statements into a try/catch. Like everyone else has said, using is for cleaning up classes that implement the IDisposable interface

try
{

 using (var conn = new SqlConnection("..."))
 {
    conn.Open();
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "...";
        using (var reader = cmd.ExecuteReader())
        {
            while (reader.Read())
            {
                // ...
            }
        }
    }
 }
}
catch(Exception ex)
{
//Handle, log, rethrow exception
}

Tags:

C#

Sql

Ado.Net