T-SQL Tutorial

TRY CATCH


TRY CATCH statement uses the TRY block to run an SQL statement and uses the CATCH block to catch the error that may occur in the TRY block. So in a TRY ... CATCH statement, the TRY block is executed first. If the TRY statement generates an error, then SQL Server executes the CATCH statement to handle the error that occurred.


Syntax

BEGIN TRY
{ sql_statement }
END TRY
BEGIN CATCH
[ { sql_statement } ]
END CATCH
[ ; ]


TRY CATCH example

The following example generates an error in the TRY block, and handles the error in the CATCH block. In the CATCH block, System Functions are used to obtain information about the generated error.

USE model
GO
BEGIN TRY
-- Generate a divide-by-zero error.
SELECT 5/0;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO


TRY CATCH example

The second example uses local variables to store information about errors generated in the TRY block. The local variables are assigned with data about the error generated inside the CATCH block.

USE model
GO
DECLARE @ErrNum int, @ErrMsg varchar(2000);
BEGIN TRY
-- Generate divide-by-zero error.
PRINT 5/0;
END TRY
BEGIN CATCH
-- Catch error number and error message.
SELECT @ErrNum=ERROR_NUMBER();
SELECT @ErrMsg=ERROR_MESSAGE();
PRINT 'ErrorNumber: '+CAST(@ErrNum AS NVARCHAR)+' ErrorMessage: '+CAST(@ErrMsg AS NVARCHAR)
END CATCH;
GO