Using try catch in SQL Server stored procedures

Overview

A great new option that has been around since SQL Server 2005 is the ability to use the Try..Catch paradigm that exists in other development languages.  Doing error handling in SQL Server has not always been the easiest thing, so this option definitely makes it much easier to code for and handle errors.

Explanation

If you are not familiar with the Try…Catch paradigm it is basically two blocks of code with your stored procedures that lets you execute some code, this is the Try section and if there are errors they are handled in the Catch section. 

Let’s take a look at an example of how this can be done.  As you can see we are using a basic SELECT statement that is contained within the TRY section, but for some reason if this fails it will run the code in the CATCH section and return the error information.

CREATE PROCEDURE dbo.uspTryCatchTest
AS
BEGIN TRY
    SELECT 1/0
END TRY
BEGIN CATCH
    SELECT ERROR_NUMBER() AS ErrorNumber
     ,ERROR_SEVERITY() AS ErrorSeverity
     ,ERROR_STATE() AS ErrorState
     ,ERROR_PROCEDURE() AS ErrorProcedure
     ,ERROR_LINE() AS ErrorLine
     ,ERROR_MESSAGE() AS ErrorMessage;
END CATCH

 

One comment

  1. Try-Catch trap errors only inside the scope of sql server…many issues are not covered this engine like lost connections ( network errors), acess ( sistem security erros ) , sql components errors ( missing or troubled dlls ) . The best alternative to solve this question is discovering the trouble before it happens like make a function that detect and return a value thats allow the main procedure to go ahead or stop because this ‘outside’ problem.

Leave a Reply

Your email address will not be published. Required fields are marked *