Microsoft® SQL Server® 2012 Bible

(Ben Green) #1

419


Chapter 16: Programming with T-SQL


16


BEGIN TRY
<SQL code>;
END TRY
BEGIN CATCH
<error handling code>;
END CATCH;

If the TRY block of code executes without any error, then the CATCH code is never exe-
cuted, and execution resumes after the CATCH block:

BEGIN TRY
SELECT 'Try One';
RAISERROR('Simulated Error', 16, 1);
Select 'Try Two';
END TRY
BEGIN CATCH
SELECT 'Catch Block';
END CATCH;
SELECT 'Post Try';

Result:

---------
Try One

------------
Catch Block

-----------
Post Try

(1 row(s) affected)

Walking through this example, SQL Server executes the TRY block until the RAISERROR’s
simulated error, which sends the execution down to the CATCH block. The entire CATCH
block is executed. Following execution of the CATCH block, execution continues with the
next statement, SELECT 'Post Try'.

The T-SQL compiler treats the END TRY... BEGIN CATCH combination as a single contiguous command. Any
other statements, a batch terminator (go), or a statement terminator (;) between these two commands, causes an
untrapped error. END TRY must be followed immediately by a BEGIN CATCH.

Catch Block
When an error does occur, the best way to trap and handle it is in the CATCH blocks. Within
the CATCH block, you want to do the following:

c16.indd 419c16.indd 419 7/30/2012 5:38:11 PM7/30/2012 5:38:11 PM


http://www.it-ebooks.info
Free download pdf