SQL Server Exception Handling

What is exception handling and how does it work in SQL Server? When developing Transact_SQL script on your SQL Server instance, you should include code that traps errors, also called exceptions) and handles them so your code continues to execute. Code written to handle these types of exceptions is known as an exception handler.

SQL Server uses TRY, CATCH blocks for exception handling. You can put your Transact-SQL statements into a TRY BLOCK and include code for exception handling in the CATCH block. You can also generate user-defined errors using a THROW block.

One of the obvious uses for exception handling is to rollback a transaction if there is an error, when using a delete, update, or insert query an there is an error, and when handling cursors in your query.

Sample Syntax

BEGIN TRY
   -- Transact-SQL Statements
END TRY
BEGIN CATCH
   -- What to do if there is an error
END CATCH

There are some basic keywords you can use in the CATCH block:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s