Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 714
Erik Larsson Avatar asked Dec 03 '11 13:12

Erik Larsson


1 Answers

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.

like image 174
bryanmac Avatar answered Sep 24 '22 20:09

bryanmac