Erik Larsson
Erik Larsson

Reputation: 2709

What exceptions to catch when dealing with SqlConnection, SqlDataReader, SqlCommand?

I'm using SqlConnection, SqlDataReader, SqlCommand and SqlParameters for communcation with my database. I'm looking for advise about catching the most relevant Exceptions instead of throwing the a new Exception(), it's a too broad class.

All help is appreciated!

Upvotes: 5

Views: 1369

Answers (1)

bryanmac
bryanmac

Reputation: 39306

The most relevant likely equates to the most common environmental conditions that can happen. Coding errors will be fixed but you can't control the environmental issues.

Also, besides the docs on the classes, you can simply try those conditions and make sure you're handling the condition properly. Years ago, a developer asked me what exception would be thrown in some various technology if connectivity was lost - so I pulled his network cable and we ran his code :)

Some common ones would be:

  1. Unplug your network cable
  2. Disable your network adapter
  3. Stop SQL Server
  4. Create a sproc that takes a very long time
  5. Let the database/tempdb get full
  6. Ensure you don't have permissions to the sql server
  7. Create a sproc that deadlocks

In some of these cases (network, timeout, deadlock victim), you'll want to retry perhaps with increasing waits. For others like db full the best you can hope for is to provide good guidance or even log details for the admin.

By trying the conditions you're assured what exception gets thrown and you can verify you're handling the condition appropriately.

Upvotes: 8

Related Questions