From the course: Complete Guide to Advanced SQL Server

Unlock the full course today

Join today to access over 24,400 courses taught by industry experts.

Capture errors with TRY and CATCH

Capture errors with TRY and CATCH - SQL Server Tutorial

From the course: Complete Guide to Advanced SQL Server

Capture errors with TRY and CATCH

In your SQL Server programs, error handling is most often implemented using TRY and CATCH blocks. The basic syntax is fairly simple. I've got an outline of what that looks like starting on Line 6 and going down to Line Number 12. At the beginning of the routine that you want to execute, add "BEGIN TRY." Then include all of the code that you want to run, assuming that it executes without any problems. After that, you'll have a line that says "END TRY," followed immediately by a BEGIN CATCH. If any errors are encountered in the TRY block, then the code in the CATCH block is executed. If the TRY block doesn't encounter any errors, then this portion is skipped over. Finish the CATCH block with END CATCH, and then you can continue on with other code that you want to execute after that. To put this into practice, let's try and execute an INSERT statement where we don't supply the values that we need for the required fields in a table. I've got that outlined here on Line Number 18 where I'm…

Contents