SQL Try Catch template

This is our example SQL TRY/CATCH template.

Why bother with templates?

RAD. Rapid Application Development.

We work remotely 99% of the time, we're not on our local machines. Templates allow us to have a place to store boilerplate (and tested) code to rapidly insert into code.

 

This is a simple way to get SQL to report errors... better. 

You get the error, and if you can get some information about where the error is coming from

DECLARE @error VARCHAR(200) = ''
BEGIN TRY
    SET @error = 'start'
    declare @a INT = 0
    print 5 / @a
    SET @error = 'end'
              
END TRY
BEGIN CATCH
    SET @error = @error + '>' +  ERROR_MESSAGE()
    RAISERROR(@error,16,2)
END CATCH

 

--this is a template for the TRY/CATCH structure
BEGIN TRY
    BEGIN TRAN
        -- be carefull not to exit this or the transaction will not get committed, you'll lock the table up
         
    COMMIT TRAN
END TRY
BEGIN CATCH
    --find out what went wrong
    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;
 
    --roll everything back
    ROLLBACK TRAN
END CATCH

RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences