Friday, November 25, 2011

SQL Server 2012 - Throwing Exception using THROW in TRY CATCH BLOCK instead of using RAISERROR

In SQL Server 2005/2008, if you want to throw an error again in catch block of TRY CATCH statement, you have to use RAISERROR with ERROR_MESSAGE(), ERROR_SEVERITY().

In SQL Server 2005/2008:
 -- EXCEPTION HANDLING in SQL Server 2005/2008  
BEGIN TRY
DECLARE @VALUE INT
SET @VALUE = 1 / 0
END TRY
BEGIN CATCH
DECLARE @Message nvarchar(4000), @Severity int
SELECT @Message = ERROR_MESSAGE(), @Severity = ERROR_SEVERITY()
RAISERROR ( @Message, @Severity, 1 )
END CATCH


SQL Server 2012:
Just, you can use THROW keyword to throw the complete error information.
 -- EXCEPTION HANDLING using THROW in SQL Server 2012  
BEGIN TRY
DECLARE @VALUE INT
SET @VALUE = 1/0
END TRY
BEGIN CATCH
THROW
END CATCH


if you execute the above statement, you will receive an error like below.
 Msg 8134, Level 16, State 1, Line 5  
Divide by zero error encountered.

No comments: