This article is half-done without your Comment! *** Please share your thoughts via Comment ***
As a DBA, I also defined the database coding standard in my organization in which I also created template for TRY – CATCH block.
For few old projects, we are still working on SQL Server 2008, but after SQL Server 2012, I had to change the format of TRY – CATCH block.
SQL Server 2012 introduced the new form of CATCH block which I am using now for all new projects where we are using SQL Server 2014/2016.
Below is a comparison between the New CATCH and Old CATCH:
The old approach of CATCH:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
BEGIN TRY DECLARE @n AS INT; SET @n = 7/0 END TRY BEGIN CATCH DECLARE @message NVARCHAR (4000) DECLARE @severity INT DECLARE @state INT SELECT @message = ERROR_MESSAGE () SELECT @severity = ERROR_SEVERITY () SELECT @state = ERROR_STATE () RAISERROR (@message,@severity,@state) END CATCH |
Error message in result:
1 2 |
Msg 50000, Level 16, State 1, Line 14 Divide by zero error encountered. |
The new approach of CATCH:
1 2 3 4 5 6 7 |
BEGIN TRY DECLARE @n AS INT SET @n = 7/0 END TRY BEGIN CATCH THROW END CATCH |
Error message in result:
1 2 |
Msg 8134, Level 16, State 1, Line 3 Divide by zero error encountered. |
Leave a Reply