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(); 
    } 
}

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

So, you mean that a try-catch block is required, and i can close the connection inside the finally clause ?
@sharonHwk You don't need try/catch/finally. Just use using and don't call cn.Close().
@MatthewWatson what hapence if there's an exception. How will i know what caused it if we aren't having a catch block here ?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.