1

I have copied the following code from here and here. I want to know is exception handling required for the following code ? What hapens if an exception is thrown before the DB connection is closed, so i think that its important to have a try-catch here.

Please give your opinion?

using System; 
using System.Data; 
using System.Data.SqlClient; 


class OutputParams 
{ 
    [STAThread] 
    static void Main(string[] args) 
    { 

    using( SqlConnection cn = new SqlConnection("server=(local);Database=Northwind;user id=sa;password=;")) 
    { 
        SqlCommand cmd = new SqlCommand("CustOrderOne", cn); 
        cmd.CommandType=CommandType.StoredProcedure ; 

        SqlParameter parm= new SqlParameter("@CustomerID",SqlDbType.NChar) ; 
        parm.Value="ALFKI"; 
        parm.Direction =ParameterDirection.Input ; 
        cmd.Parameters.Add(parm); 

        SqlParameter parm2= new SqlParameter("@ProductName",SqlDbType.VarChar); 
        parm2.Size=50; 
        parm2.Direction=ParameterDirection.Output; 
        cmd.Parameters.Add(parm2); 

        SqlParameter parm3=new SqlParameter("@Quantity",SqlDbType.Int); 
        parm3.Direction=ParameterDirection.Output; 
        cmd.Parameters.Add(parm3);

        cn.Open(); 
        cmd.ExecuteNonQuery(); 
        cn.Close(); 

        Console.WriteLine(cmd.Parameters["@ProductName"].Value); 
        Console.WriteLine(cmd.Parameters["@Quantity"].Value.ToString());
        Console.ReadLine(); 
    } 
}
Community
  • 1
  • 1
Sharon Watinsan
  • 9,620
  • 31
  • 96
  • 140

1 Answers1

2

The using directive is expanded as try...finally so it makes sense to nest that inside a try... catch block.

P.S: there is no need to use cn.Close() as finally block essentially does that.

naveen
  • 53,448
  • 46
  • 161
  • 251
  • So, you mean that a try-catch block is required, and i can close the connection inside the finally clause ? – Sharon Watinsan May 26 '13 at 16:18
  • please see this link: http://stackoverflow.com/questions/13082590/c-using-directive-and-try-catch-block – naveen May 26 '13 at 16:21
  • 1
    @sharonHwk You don't need try/catch/finally. Just use `using` and don't call `cn.Close()`. – Matthew Watson May 26 '13 at 16:27
  • @MatthewWatson what hapence if there's an exception. How will i know what caused it if we aren't having a catch block here ? – Sharon Watinsan May 26 '13 at 16:33
  • 1
    @sharonHwk Normally exceptions should be caught at a higher level. The higher level code can catch exceptions and log them or whatever. You should only catch an exception if you know how to respond to it. Of course if this is your main program method then it *is* the right place, but it looks like test code to me. – Matthew Watson May 26 '13 at 16:50