0

I am running a service that queries on regular intervals. I initially set it up so that the connection formed onStart, and closed onStop. This of course leaves a connection open all the time, which isn't what I want. So I moved the open and closed to inside my timer event handler.

My question: Is there a difference between

try{connection.Open();}
catch{error;}
someAction();
try{connection.Close();}
catch(Exception)
{error}

and

try{ connection.Open();
someAction(); 
connection.Close();
}
catch(Exception)
{error}

If so which is better?

4
Contributors
4
Replies
5
Views
10 Years
Discussion Span
Last Post by seahmadmom
0

kinda hard to tell, but what happens with your first example if there is an exception during someAction()

0

I am running a service that queries on regular intervals. I initially set it up so that the connection formed onStart, and closed onStop. This of course leaves a connection open all the time, which isn't what I want. So I moved the open and closed to inside my timer event handler.

My question: Is there a difference between

try{connection.Open();}
catch{error;}
someAction();
try{connection.Close();}
catch(Exception)
{error}

and

try{ connection.Open();
someAction(); 
connection.Close();
}
catch(Exception)
{error}

If so which is better?

Why not just use a using statement? Then you don't have to worry about closing the connection. :)

try {
  using ( connection = new SqlConnection( connectionString ) ) {
    someAction();
  }
}
catch ( Exception ) {
  // Error
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.