C# using statement catch error

后端 未结 16 1301
轻奢々
轻奢々 2021-01-30 14:06

I am just looking at the using statement, I have always known what it does but until now not tried using it, I have come up with the below code:

 using (SqlComma         


        
相关标签:
16条回答
  • 2021-01-30 14:34

    This code should be as follows to ensure timely closing of the connection. Closing just the command doesn't close the connection:

    using (SqlConnection con = new SqlConnection(Settings.Default.qlsdat_extensionsConnectionString))
    using (SqlCommand cmd = new SqlCommand(reportDataSource, con))
             {
                 cmd.CommandType = CommandType.StoredProcedure;
                 cmd.Parameters.Add("@Year", SqlDbType.Char, 4).Value = year;
                 cmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = start;
                 cmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = end;
                 cmd.Connection.Open();
    
                 DataSet dset = new DataSet();
                 new SqlDataAdapter(cmd).Fill(dset);
                 this.gridDataSource.DataSource = dset.Tables[0];
             }
    

    To answer your question, you can do the same in a finally block, but this scopes the code nicely and ensures that you remember to clean up.

    0 讨论(0)
  • 2021-01-30 14:35

    There are a lot of great answers here, but I don't think this has been said yet.

    No matter what... the "Dispose" method WILL be called on the object in the "using" block. If you put a return statement, or throw an error, the "Dispose" will be called.

    Example:

    I made a class called "MyDisposable", and it implements IDisposable and simply does a Console.Write. It always writes to the console even in all these scenarios:

    using (MyDisposable blah = new MyDisposable())
    {
        int.Parse("!"); // <- calls "Dispose" after the error.
    
        return; // <-- calls Dispose before returning.
    }
    
    0 讨论(0)
  • 2021-01-30 14:36

    Yes you would still need to catch exceptions. The benefit of the using block is you are adding scope to your code. You are saying, "Within this block of code do some stuff and when it gets to the end, close and dispose of resources"

    It's not completely necessary at all, but it does define your intentions to anyone else using your code, and it also helps not leaving connections etc open by mistake.

    0 讨论(0)
  • 2021-01-30 14:37

    There may be no advantage to using a using statement in this case if you're going to have a try/catch/finally block anyway. As you know, the using statement is syntactic sugar for a try/finally that disposes of the IDisposable object. If you're going to have your own try/finally anyway, you can certainly do the Dispose yourself.

    This really mainly boils down to style - your team may be more comfortable with using statements or using statements may make the code look cleaner.

    But, if the boilerplate the using statement would be hiding is there anyway, go ahead and handle things yourself if that's your preference.

    0 讨论(0)
  • 2021-01-30 14:40

    Elaborating on what Chris Ballance said, the C# specification (ECMA-334 version 4) section 15.13 states "A using statement is translated into three parts: acquisition, usage, and disposal. Usage of the resource is implicitly enclosed in a try statement that includes a finally clause. This finally clause disposes of the resource. If a null resource is acquired, then no call to Dispose is made, and no exception is thrown."

    The description is close to 2 pages - worth a read.

    In my experience, SqlConnection/SqlCommand can generate errors in so many ways that you almost need to handle the exceptions thrown more than handle the expected behaviour. I'm not sure I'd want the using clause here, as I'd want to be able to handle the null resource case myself.

    0 讨论(0)
  • 2021-01-30 14:40

    one issue with "using" is that it doesn't handles exceptions. if the designers of "using" would add "catch" optionally to its syntax like below pseudocode, it would be much more useful:

    using (...MyDisposableObj...)
    {
    
       ... use MyDisposableObj ...
    
    catch (exception)
    
       ... handle exception ...
    
    }
    
    it could even have an optional "finally" clause to cleanup anything other than the "MyDisposableObj" allocated at the beginning of the "using" statement... like:
    
    using (...MyDisposableObj...)
    {
    
       ... use MyDisposableObj ...
       ... open a file or db connection ...
    
    catch (exception)
    
       ... handle exception ...
    
    finally
    
       ... close the file or db connection ...
    
    }
    

    still there'll be no need to write code to dispose of MyDisposableObj b/c it'd be handled by using...

    How do like that?

    0 讨论(0)
提交回复
热议问题