Search code examples
c#exceptionsqlconnection

Test sql connection without throwing exception


To test if i can connect to my database, I execute the following code :

using (SqlConnection connection = new SqlConnection(myConnectionString))
{
   try
   {
      connection.Open();
      canConnect = true;
   }
   catch (SqlException) { }
}

This works except it throws an exception if the connection failed. Is there any other way to test a Sql connection that doesn't throw an exception ?

Edit : To add precision, i'm asking if there is a simple method that does that without having to open the connection and catch exceptions that can occur


Solution

  • 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.