THROW
Statement
THROW statement raises an exception and transfers execution to a CATCH block of a TRY…CATCH construct in SQL Server 2012.
Syntax:
THROW [ { error_number | @local_variable },
{ message | @local_variable },
{ state | @local_variable }
] [ ; ]
Examples:
USE tempdb;
GO
CREATE TABLE dbo.TestRethrow
( ID INT PRIMARY KEY
);
BEGIN TRY
INSERT dbo.TestRethrow(ID) VALUES(1);
-- Force error 2627, Violation of PRIMARY KEY constraint to be raised.
INSERT dbo.TestRethrow(ID) VALUES(1);
END TRY
BEGIN CATCH
PRINT 'In catch block.';
THROW;
END CATCH;
PRINT 'In catch block.';
Msg 2627, Level 14, State 1, Line 1
Violation of PRIMARY KEY constraint 'PK__TestReth__3214EC272E3BD7D3'. Cannot insert duplicate key in object 'dbo.TestRethrow'.
The statement has been terminated.
THROW statement raises an exception and transfers execution to a CATCH block of a TRY…CATCH construct in SQL Server 2012.
Syntax:
THROW [ { error_number | @local_variable },
{ message | @local_variable },
{ state | @local_variable }
] [ ; ]
The
statement before the THROW statement must be followed by the semicolon (;)
statement terminator.
If a TRY…CATCH construct is not
available, the session is ended. The line number and procedure where the
exception is raised are set. The severity is set to 16.
If the
THROW statement is specified withoutü parameters, it must appear inside a CATCH block. This causes the
caught exception to be raised. Any error that occurs in a THROW statement
causes the statement batch to be ended.
Differences Between RAISERROR and THROW
Examples:
USE tempdb;
GO
CREATE TABLE dbo.TestRethrow
( ID INT PRIMARY KEY
);
BEGIN TRY
INSERT dbo.TestRethrow(ID) VALUES(1);
-- Force error 2627, Violation of PRIMARY KEY constraint to be raised.
INSERT dbo.TestRethrow(ID) VALUES(1);
END TRY
BEGIN CATCH
PRINT 'In catch block.';
THROW;
END CATCH;
PRINT 'In catch block.';
Msg 2627, Level 14, State 1, Line 1
Violation of PRIMARY KEY constraint 'PK__TestReth__3214EC272E3BD7D3'. Cannot insert duplicate key in object 'dbo.TestRethrow'.
The statement has been terminated.
