17.07.2015 Views

Defensive Database Programming - Red Gate Software

Defensive Database Programming - Red Gate Software

Defensive Database Programming - Red Gate Software

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 8: <strong>Defensive</strong> Error HandlingCode---------- -------------------------------------ILIL, Ill.IL Illinois, ?Listing 8-25: Checking that the data is in the expected state.In short, C# allows us to implement our "retry after deadlock" logic just once and reuseit as many times as we need. As defensive programmers, we really want to reuse ourcode, not to cut and paste the same code all over our systems, and so we have a strongmotivation to use a good modern tool such as C# for our error handling.My message here is quite moderate. I am not suggesting that we abandon T-SQL errorhandling; far from it. In the simplest cases, when all we need is to roll back and raise anerror, we should use XACT_ABORT and transactions. Notice that in Listing 8-23 we useXACT_ABORT and a transaction to roll back after a deadlock, but we implement all ofthe more complex error-handling logic in C#.Of course, there are situations when we do need to implement error handling in T-SQL.Whenever we are considering such an option, we need to realize that error handling inT-SQL is very complex and not really intuitive to a developer with experience in otherlanguages. Also, it has a lot of gotchas, and it lacks some features which client-sideprogrammers consider as their birthright, such as the ability to re-throw an error exactlyas it was caught.ConclusionIt is essential that the defensive database programmer includes robust error handlingin all production T-SQL code. However, as much as the introduction of TRY…CATCHhas improved error handling in T-SQL, it still lacks the versatility, elegance and ease ofuse that is typical of client-side languages such as Java and C#. Ultimately, you will findthat it is not possible to handle certain errors in Transact SQL at all and that we need tocomplement our T-SQL error handling with error handling on the client.290

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!