Quantcast
Channel: Denali – SQLXpertise
Viewing all articles
Browse latest Browse all 8

Catch ‘n Throw Errors in SQL Server “Denali”

$
0
0

SQL Server “Denali” adds a new feature in Error Handling called “THROW”

Current version already has RAISERROR, which you can already use to raise Error from your procedures, then why do we need this new “THROW” option,

Let us see the differences

/* RAISERROR */

BEGIN TRY
    SELECT 1/0
END TRY
BEGIN CATCH

    DECLARE @ERRORNUMBER INT = ERROR_NUMBER()
    DECLARE @ERRORMESSAGE VARCHAR(500) = ERROR_MESSAGE()

    SELECT @ERRORNUMBER, @ERRORMESSAGE

    RAISERROR(@ERRORNUMBER, 16, -1)
END CATCH

In the above code, we are creating Divide by Zero error in the Try Block and then Catching that Error in Catch Block and Display the Error details and then need to return the same error to calling application

Output from SELECT:

image

Msg 2732, Level 16, State 1, Line 11 Error number 8134 is invalid. The number must be from 13000 through 2147483647 and it cannot be 50000.

RAISERROR(@ERRORNUMBER, 16, –1) causes the above error instead of returning that error to application

See the same implementation using THROW and how it works

/* THROW Demo */

BEGIN TRY
    SELECT 1/0
END TRY
BEGIN CATCH
    PRINT 'Error Number: ' + CAST(ERROR_NUMBER() AS VARCHAR);
    PRINT 'Error Line: ' + CAST(ERROR_LINE() AS VARCHAR);

    THROW;
END CATCH 
(0 row(s) affected)
Error Number: 8134
Error Line: 5
Msg 8134, Level 16, State 1, Line 5
Divide by zero error encountered.

 

The Error number and Error Line was printed and then the same error was thrown back to calling application

You can use THROW to log errors in CATCH block and return the same error back to calling application easily.


Filed under: SQL Server, SQL Server "Denali" Tagged: Denali, RAISERROR, SQL Server, SQL Server Denali, T-SQL, THROW

Viewing all articles
Browse latest Browse all 8

Latest Images

Trending Articles





Latest Images