Introduction
If you review the Books Online, you will find the SQL Server 2012 documentation is recommending not to use RAISERROR for future code as it will be removed in future releases. It recommends to use the Throw statement instead.
Why is RAISERROR going to be removed? Well, there obvious answers:
- THROW is a standard for error handling. All the C, C#, java programmers will feel really comfortable with the THROW statement.
- There are some errors when RAISERROR is combined with the TRY, CATCH options, especially when we change the severity.
Getting started with the Throw statement
Let’s play with a simple example of the THROW usage:
THROW 50000, 'This is the error message.', 1;
Here 50000 is the error number and state is used as a reference to find the error in the code. 1 is the state of the error. The state can be a number from 0 to 255. It is used to know the location of the code where it fails.
If you notice, it is similar to RAISERROR, but it does not include the severity.
RAISERROR (N'This is the error message',16,1);
By default, the Throw statement always has the severity of 16.
THROW USED IN A TRY CATCH SENTENCE
The following example is a typical try, catch sentence. In this example, we are forcing a divide by 0 operation. The @value1 is inside the TRY and the THROW will throw the error message expected.
BEGIN TRY declare @value1 int = 2/0 END TRY BEGIN CATCH PRINT 'Error divide by 0'; THROW END CATCH
The error message displayed by the statement is:
Error divide by 0
Msg 8134, Level 16, State 1, Line 2
Divide by zero error encountered.
Disadvantages of the Throw statement.
- Throw does not include the WITH LOG option included by RAISERROR which let us log information in the ERROR and application log.
- We do not have now the nice printf options that we had in the past to manage variables.
Advantages of the Throw statement.
- We do not need to use and handle the sys.messages view, add messages, remove messages.
- It is a standard method to handle errors.
- The function is shorter and uses less parameters.
Conclusion
The new SQL Server 2012 is adding a nice useful and standard statement to handle error messages. The old Raiserror will be replaced in the future with the new Throw option.
References
http://msdn.microsoft.com/en-us/library/ms178592(v=sql.110).aspx
THROW
http://msdn.microsoft.com/en-us/library/ee677615(v=sql.110).aspx