Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

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

Comments

Posted by Anonymous on 7 July 2011

Pingback from  Dew Drop – July 7, 2011 | Alvin Ashcraft's Morning Dew

Posted by Anonymous on 8 July 2011

Pingback from  Dew Drop – July 8, 2011 | Alvin Ashcraft's Morning Dew

Leave a Comment

Please register or log in to leave a comment.