How to rethrow the same exception in SQL Server How to rethrow the same exception in SQL Server database database

How to rethrow the same exception in SQL Server


SQL 2012 introduces the throw statement:

http://msdn.microsoft.com/en-us/library/ee677615.aspx

If the THROW statement is specified without parameters, it must appear inside a CATCH block. This causes the caught exception to be raised.

BEGIN TRY    BEGIN TRANSACTION    ...    COMMIT TRANSACTIONEND TRYBEGIN CATCH    ROLLBACK TRANSACTION;    THROWEND CATCH


Here is a fully functional clean code sample to rollback a series of statements if an error occurs and reports the error message.

begin try    begin transaction;    ...    commit transaction;end trybegin catch    if @@trancount > 0 rollback transaction;    throw;end catch

Before SQL 2012

begin try    begin transaction;        ...        commit transaction;end trybegin catch    declare @ErrorMessage nvarchar(max), @ErrorSeverity int, @ErrorState int;    select @ErrorMessage = ERROR_MESSAGE() + ' Line ' + cast(ERROR_LINE() as nvarchar(5)), @ErrorSeverity = ERROR_SEVERITY(), @ErrorState = ERROR_STATE();    if @@trancount > 0 rollback transaction;    raiserror (@ErrorMessage, @ErrorSeverity, @ErrorState);end catch


I think your choices are:

  • Dont catch the error (let it bubble up)
  • Raise a custom one

At some point, SQL will probably introduce a reraise command, or the ability to catch only certain errors. But for now, use a workaround. Sorry.