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 HandlingBEGIN TRY ;PRINT 'Beginning TRY block' ;SELECT COUNT(*)FROM #NoSuchTempTable ;PRINT 'Ending TRY block' ;END TRYBEGIN CATCH ;PRINT 'Entering CATCH block' ;END CATCH ;PRINT 'After the end of the CATCH block' ;Beginning TRY blockMsg 208, Level 16, State 0, Line 3Invalid object name '#NoSuchTempTable'.Listing 8-19: Sometimes a CATCH block is bypassed when an error occurs.Even more surprising for object-oriented developers is that this is not a bug; it is just theway SQL Server works in this case. According to MSDN for SQL Server 2008:"Errors that occur during statement-level recompilation…are not handled by a CATCHblock when they occur at the same level of execution as the TRY…CATCH construct."The issue here is that compilation errors that occur at run time (as a result of deferredname resolution) abort the rest of the scope, which is equal to the batch in directlysubmitted SQL, but only equal to the rest of the procedure in a stored procedure orfunction. So a TRY…CATCH at the same scope will not intercept these errors, but a TRY…CATCH on a different scope (regardless of being nested or not) will catch it.My point here is simple: SQL Server does not always handle errors in a way objectorientedlanguages do. If we choose to use the error handling provided by SQL Server,we really need to learn it in detail or we will be in for some unpleasant surprises.280

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

Saved successfully!

Ooh no, something went wrong!