Sunday, October 17, 2021

Re-throwing exception generated by RAISERROR

 You can re-throw error that you catch in CATCH block using TRHOW statement:

DECLARE @msg nvarchar(50) = 'Here is a problem! Area: ''%s'' Line:''%i'''
BEGIN TRY
	print 'First statement';
	RAISERROR(@msg, 11, 1, 'TRY BLOCK', 2);
	print 'Second statement';
END TRY
BEGIN CATCH
	print 'Error: ' + ERROR_MESSAGE();
	THROW;
END CATCH

Output:

First statement

Error: Here is a problem! Area: 'TRY BLOCK' Line:'2'

Msg 50000, Level 11, State 1, Line 4

Here is a problem! Area: 'TRY BLOCK' Line:'2'

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.


No comments:

Post a Comment