Saturday, September 4, 2010

try catch with RAISEERROR function

here we can learn how to use try catch block in sql server

as a programmer i never use try catch block in any of my query or store procedure,

but recently i got stuck in one store procedure, My SP not executed & i didnt get exact error message also,


after searching i got solution that using try catch block with RAISEERROR finction i can catch the exact error, so using this i got exact error, & i solved that within a second

so it is a good practice to use try catch in sql.

RAISEERROR function gives us exact error definition.


Example 1 : Simple TRY…CATCH without RAISEERROR function
BEGIN TRY
DECLARE @MyInt INT;
-- Following statement will create Devide by Zero Error
SET @MyInt = 1/0;
END TRY
BEGIN CATCH
SELECT 'Divide by zero error encountered.' ErrorMessage
END CATCH;
GO

ResultSet:
ErrorMessage
———————————
Divide by zero error encountered.

Example 2 : Simple TRY…CATCH with RAISEERROR function
BEGIN TRY
DECLARE @MyInt INT;
-- Following statement will create Devide by Zero Error
SET @MyInt = 1/0;
END TRY
BEGIN CATCH
DECLARE @ErrorMessage NVARCHAR(4000);
SELECT @ErrorMessage = ERROR_MESSAGE();
RAISERROR (@ErrorMessage, 16, 1);
END CATCH;
GO

ResultSet:
Msg 50000, Level 16, State 1, Line 9
Divide by zero error encountered.

1 comment:

  1. Good one ,

    Even u can track more details of error like
    ErrorNumber,ErrorState,ErrorProcedure with below in build functions.

    Note : Try.Catch doesnt catch errors having
    Severity > 16.

    SELECT
    ERROR_NUMBER() AS ErrorNumber,
    ERROR_SEVERITY() AS ErrorSeverity,
    ERROR_STATE() AS ErrorState,
    ERROR_PROCEDURE() AS ErrorProcedure,
    ERROR_LINE() AS ErrorLine,
    ERROR_MESSAGE() AS ErrorMessage;

    ReplyDelete