Skip to content
Advertisement

Correct use of Try Catch for the SQL connection in C#

Is this code correct in means of Try/Catch? I need to value whether the action is done or not to inform the user about the result, so I will then get the bool value to know if connection was successful.

Advertisement

Answer

Your method can actually have 3 outcomes:

  1. The table was created successfully (method returns true)
  2. The table already exists (method returns false)
  3. There was an error trying to create the table (exception is thrown)

So you should handle the exception outside of this method and you should not blindly catch all Exceptions. You should only handle the SqlException so that other exceptions will not be handled. Also you should be logging the exception somewhere as a good practice.

For more information on the SqlException
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlexception(v=vs.110).aspx

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement