Microsoft SQL Server Throwing exception in TRY/CATCH blocks


Example

You can throw exception in try catch block:

DECLARE @msg nvarchar(50) = 'Here is a problem!'
BEGIN TRY
    print 'First statement';
    THROW 51000, @msg, 15;
    print 'Second statement';
END TRY
BEGIN CATCH
    print 'Error: ' + ERROR_MESSAGE();
    THROW;
END CATCH

Exception with be handled in CATCH block and then re-thrown using THROW without parameters.

First statement
Error: Here is a problem!
Msg 51000, Level 16, State 15, Line 39
Here is a problem!

THROW is similar to RAISERROR with following differences:

  • Recommendation is that new applications should use THROW instead of RASIERROR.
  • THROW can use any number as first argument (error number), RAISERROR can use only ids in sys.messages view
  • THROW has severity 16 (cannot be changed)
  • THROW cannot format arguments like RAISERROR. Use FORMATMESSAGE function as an argument of RAISERROR if you need this feature.