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?

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

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 article has been dead for over six months. Start a new discussion instead.