Friday, April 20, 2012

Try Catch In SQL Server

Try /  Catch introduced from SQL Server 2005 onwards, which helps to track the error messages occured in the program block.

Syntax
TRY
     Set of T-SQL Statements
END TRY
BEGIN CATCH
     Set of T-SQL Statements
END CATCH

The catch block will execute statements only if error occured on the TRY Block.

Simple Example

If you execute the below command
select 1/0
It gives the error message  Msg 8134, Level 16, State 1, Line 1 Divide by zero error encountered.
To handle any kind of errors we can use Try / Catch Construct



Begin Try
Select 1/0
End Try
Begin Catch
Select 'Error Occured'Select 'Error Occured'
End Catch

BEGIN TRY
select 1/0
End Try
Begin Catch
Select ERROR_NUMBER(), ERROR_MESSAGE(), ERROR_SEVERITY(),
ERROR_STATE()
RAISERROR ('NUMERIC ERROR',11,1) WITH LOG
-- Logged into Event Viewer as a informational message
RAISERROR ('NUMERIC ERROR',16,1) WITH LOG
-- Logged into Event Viewer as a Error Message .
End Catch

No comments: