Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't 'using' have a catch block?

I understand the point of "using" is to guarantee that the Dispose method of the object will be called. But how should an exception within a "using" statement be handled? If there is an exception, I need to wrap my "using" statement in a try catch. For example:


Lets say there is an exception created in the creation of the object inside the using parameter

 try
 {
    // Exception in using parameter
    using (SqlConnection connection = new SqlConnection("LippertTheLeopard"))
    {
       connection.Open();
    }
 }
 catch (Exception ex)
 {

 }

Or an Exception within the using scope

 using (SqlConnection connection = new SqlConnection())
 {
    try
    {
       connection.Open();
    }
    catch (Exception ex)
    {

    }
 }

It seems like if I already need to handle an exception with a try catch, that maybe I should just handle the disposing of the object as well. In this case the "using" statement doesn't seem to help me out at all. How do I properly handle an exception with "using" statement? Is there a better approach to this that I'm missing?

 SqlConnection connection2 = null;
 try
 {
    connection2 = new SqlConnection("z");
    connection2.Open();
 }
 catch (Exception ex)
 {

 }
 finally
 {
    IDisposable disp = connection2 as IDisposable;
    if (disp != null)
    {
       disp.Dispose();
    }
 }

Could the "using" keyword syntax be a little more sugary...
It sure would be nice to have this:

 using (SqlConnection connection = new SqlConnection())
 {
    connection.Open();
 }
 catch(Exception ex)
 {
   // What went wrong? Well at least connection is Disposed
 }
like image 825
SwDevMan81 Avatar asked Nov 12 '09 19:11

SwDevMan81


2 Answers

Because you would be 'hiding' extra functionality inside an unrelated keyword.

However you could always write it this way

using (...) try
{
}
catch (...)
{
}

And this way the line represents your intentions -- a using statement that is also a try

like image 183
Kevin Laity Avatar answered Oct 11 '22 03:10

Kevin Laity


using Has nothing to do with error handling. It's shorthand for "call Dispose when you leave this block." Your second code example is perfectly acceptable... why mess with what works?

like image 22
Dave Swersky Avatar answered Oct 11 '22 03:10

Dave Swersky