Test sql connection without throwing exception

When attempting to open a connection, there is no way to avoid the exception if the connection can't be opened. It can be hidden away in a function somewhere, but you're going to get the exception, no matter what.

It was designed like this because generally you expect to be able to connect to the database. A failed connection is the exception.

That being said, you can test the current connection state at any time by checking the State property.


write an extension like so:

public static class Extension{
 public static bool CanOpen(this SqlConnection connection){
   try{
    if(connection == null){ return false; }

    connection.Open();
    var canOpen = connection.State == ConnectionState.Open;
    connection.close();
    return canOpen;
 }
 catch{
  return false;
 }
}

Then you can consume it like:

 using(var connection = new SqlConnection(myConnectionString)){
      if(connection.CanOpen()){
       // NOTE: The connection is not open at this point...
       // You can either open it here or not close it in the extension method...
       // I prefer opening the connection explicitly here...
     }
}

HTH.


If it throws an an exception and you handle it in your catch block you already know the connection failed. I think you answered your own question.