Problem:
How to raise system error without specifying message, state, level.
Throw is a control flow language
which is new error handling functionality introduced in SQL server 2012 and
above.
Throw has some good amount of
differences between RAISERROR.
RAISERROR statement
|
THROW statement
|
If a msg_id is passed to
RAISERROR, the ID must be defined in sys.messages.
|
The error_number parameter
does not have to be defined in sys.messages.
|
The msg_str parameter can
contain printf formatting styles.
|
The message parameter does
not accept printf style formatting.
|
The severity parameter
specifies the severity of the exception.
|
There is no severity parameter.
The exception severity is always set to 16.
|
For all the newer applications
THROW should be used for coding efficiency and also benefits from THROW.
Example:
In this article I am going to show you we can use THROW inside a
TRY/CATCH block.
Example 1: In this example, I would
like to show how we can use throw and show how code executes when there is an
exception in the code.
THROW
|
RAISERROR
|
|
BEGIN
BEGIN TRY SELECT 1 / 0 END TRY BEGIN CATCH PRINT 'In catch block.'; THROW; END CATCH; PRINT 'still running code' END |
BEGIN
BEGIN TRY SELECT 1 / 0 END TRY BEGIN CATCH PRINT 'In catch block.'; RAISERROR ('error',16,1 ) END CATCH; PRINT 'still running code' END |
|
OUTPUT:
THROW RAISERROR
(0 row(s) affected) In catch block. Msg 8134, Level 16, State 1, Line 3 Divide by zero error encountered. |
(0 row(s) affected)
In catch block. Msg 50000, Level 16, State 1, Line 9 error (1 row(s) affected) still running code |
|
From the above output we can see that
throw stops the execution but raise error still executes the code.
Print statement executes in the
case of raise error but throw exits from the code.
0 comments:
Post a Comment