Blog Post

Less code with rethrowing “exception” in SQL Server 2011

,

I wrote about some skeletons in the Denali’s closet here. Let’s also put some good on the table. Very handy new thing in Denali is the way how you can rethrow error in catch block.

In SQL Server 2008 you must do this to rethrow error:

BEGIN TRY
    -- plenty of code or function/procedures invocation 
    -- where you don't have any error handling 
    -- will it work?
    SELECT 1/0
END TRY
BEGIN CATCH
    DECLARE @errorid INT = ERROR_NUMBER()
    DECLARE @proc VARCHAR(200) = ERROR_PROCEDURE()
    DECLARE @ErrorMessage VARCHAR(200) = ERROR_MESSAGE()
    DECLARE @Severity INT = ERROR_SEVERITY()
    DECLARE @State INT = ERROR_STATE()
    SET @ErrorMessage = 'My error - ' + @ErrorMessage
    RAISERROR(@ErrorMessage, @Severity, @State) 
END CATCH

In SQL Server 2011 you can simply use THROW keyword:

BEGIN TRY
    -- plenty of code or function/procedures invocation 
    -- where you don't have any error handling 
    -- will it work?
    SELECT 1/0
END TRY
BEGIN CATCH
    THROW
END CATCH

I like that but question is who will re-write my existing code :)

Jakub Dvorak @ www.sqltreeo.com

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating