SQL Server 2012 - THROW - Enhancement in error handling using TRY CATCH


THROW  statement can be used to raise an exception,like RAISERROR

Syntax : 

THROW [ { error_number | @local_variable },
        { message | @local_variable },
    { state | @local_variable }
] [ ; ]

error_number
 error_number is int and must be greater than or equal to 50000 and less than or equal to 2147483647.
message
message is nvarchar(2048).
state
 between 0 and 255 that indicates the state to associate with the message. state is tinyint.

EXAMPLES:

-- Exceptions raised by THROW statement will always have a severity of 16

THROW 50000, 'Exceptions raised by THROW statement will always have a severity of 16 ', 1;
THROW 2147483647, 'Exceptions raised by THROW statement will always have a severity of 16 ', 1;
 
--The statement before the THROW statement must be followed by the semicolon (;) statement terminator.
USE AdventureWorks2012

CREATE PROCEDURE THROW_Example
AS
BEGIN
SET NOCOUNT ON

BEGIN TRY
DELETE FROM [HumanResources].[Employee] WHERE BusinessEntityID = 1
END TRY

BEGIN CATCH
SELECT 'The statement before the THROW statement must be followed by the semicolon (;) statement terminator';
THROW
END CATCH

END
GO
EXECUTE THROW_Example

GO



 For more information  & differences between the RAISERROR and THROW statements - http://msdn.microsoft.com/en-us/library/ee677615.aspx
Structured Error Handling Mechanism in SQL Server 2012 -  http://social.technet.microsoft.com/wiki/contents/articles/20002.structured-error-handling-mechanism-in-sql-server-2012.aspx 

No comments: