T-SQL Tutorial

THROW


The THROW statement is used to catch errors in a SQL Server block. Throw can be used with optional arguments such as: error_number, message, state.


Syntax

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


THROW example

THROW 51000, 'No record found.', 1;


THROW with variable

DECLARE @ErrMsg NVARCHAR(200)
SET @ErrMsg = 'My Error!'
;THROW 60000, @ErrMsg, 1


THROW in block

In the following example, I created a table with a single column declared as the primary key. The column is of varchar type with length 2. In the TRY block, the first two records are correctly inserted, then an attempt is made to insert a record that exceeds the length of the column, so that it will generate an error and the last insert will be skipped. In the CATCH block we use THROW to catch the error.

USE model
GO
CREATE TABLE myTable
(ID varchar(2) PRIMARY KEY);
BEGIN TRY
INSERT myTable(ID) VALUES('A');
INSERT myTable(ID) VALUES('B');
INSERT myTable(ID) VALUES('AAA');
INSERT myTable(ID) VALUES('C');
END TRY
BEGIN CATCH
PRINT 'Error in try catch block';
THROW;
END CATCH;
GO