THROW

Transactions and Error Handling in SQL Server

Miriam Antona

Software Engineer

THROW syntax

  • Recommended by Microsoft over the RAISERROR statement.
THROW [ error_number, message, state ][ ; ]
Transactions and Error Handling in SQL Server

THROW - without parameters

BEGIN TRY
    SELECT price/0 from orders;
END TRY
BEGIN CATCH
    THROW;    
    SELECT 'This line is executed!' as message;
END CATCH
(0 rows affected) 
Msg. 8134, Level 16, State 1, Line 2
Divide by zero error encountered.
Transactions and Error Handling in SQL Server

THROW - ambiguity

BEGIN TRY
    SELECT price/0 from orders;
END TRY
BEGIN CATCH
    SELECT 'This line is executed!'
    THROW;
END CATCH
| THROW                  |
|------------------------|
| This line is executed! |
Transactions and Error Handling in SQL Server

THROW - ambiguity

BEGIN TRY
    SELECT price/0 from orders;
END TRY
BEGIN CATCH
    SELECT 'This line is executed!';
    THROW;
END CATCH
| (No column name)       |
|------------------------|
| This line is executed! |
(0 rows affected) 
(1 rows affected)
Msg. 8134, Level 16, State 1, Line 2
Divide by zero error encountered.
Transactions and Error Handling in SQL Server

THROW - with parameters

THROW error_number, message, state [ ; ]
THROW 52000, 'This is an example', 1;
Msg. 52000, Level 16, State 1, Line 1
This is an example
Transactions and Error Handling in SQL Server

THROW - with parameters

BEGIN TRY
    IF NOT EXISTS (SELECT * FROM staff WHERE staff_id = 15)
        THROW 51000, 'This is an example', 1;
END TRY
BEGIN CATCH
    SELECT ERROR_MESSAGE() AS message;
END CATCH
| THROW                      |
|----------------------------|
| This is an example         |
Transactions and Error Handling in SQL Server

Let's practice!

Transactions and Error Handling in SQL Server

Preparing Video For Download...