Wednesday, December 24, 2014

TRY..CATCH block - RAISERROR - THROW statement



execution to stop, you need to raise the error within the TRY block
 and then raise the error again in your CATCH block this will make sure that the error is "raised" to the caller.
 Or you could add a RETURN statement after your RAISERROR statement in the CATCH block. This will exit the procedure and return to the caller.

Also, as suggested by MSDN you should try to use the THROW statement instead of RAISERROR since it (the RAISERROR) will be phased out.

RETURN following the RAISERROR() in the CATCH block and the stored proc works fine now.

Source:When does RAISERROR fire in a stored procedure?

 

That's not how it works in T-SQL. Nothing in the documentation for TRY...CATCH or RAISERROR specifies any special cases that would override:
When the code in the CATCH block finishes, control passes to the statement immediately after the END CATCH statement. Errors trapped by a CATCH block are not returned to the calling application. If any part of the error information must be returned to the application, the code in the CATCH block must do so by using mechanisms such as SELECT result sets or the RAISERROR and PRINT statements.
If you want the stored proc to exit, you need a RETURN statement as well.
....
It depends on the severity level that you use. There's a lot more information in the below link:
But to quote the article:
The errors generated by RAISERROR operate the same as errors generated by the Database Engine code. The values specified by RAISERROR are reported by the ERROR_LINE, ERROR_MESSAGE, ERROR_NUMBER, ERROR_PROCEDURE, ERROR_SEVERITY, ERROR_STATE, and @@ERROR system functions. When RAISERROR is run with a severity of 11 or higher in a TRY block, it transfers control to the associated CATCH block. The error is returned to the caller if RAISERROR is run...
So if your severity level is 11 or higher then the control will be immediately transferred to the CATCH block.

 






No comments:

Post a Comment