SQL Server – Error handling using Throw
MS-SQL Server 2012 introduced a new way of error handling using THROW statement. Prior to SQL Server 2012 we had to use RAISEERROR for error handling.
Throw statement raises an exception and transfers the execution to a CATCH block of a TRY…CATCH construct. Session will be ended if Throw is used without TRY…CATCH construct.
Syntax:
THROW [ { error_number | @local_variable },
{ message | @local_variable },
{ state | @local_variable }
] [ ; ]
To use error number in throw statement, it is not required to add the message in sys.messages table but the error number should be greater than equal to 50000. It can only raise severity of 16. Throw can be used without parameter in side CATCH construct.
You can find the difference between THROW and RAISERROR here.
The interesting point about throw is that you can re-throw the original error information from the catch block without passing any parameter.
Example:
Begin Try
print 'Start'
Begin Try
Declare @Name varchar(20) = '$XYZ'
If (LEFT(@Name,1)='$')
Begin
Throw 51234,'Name should not starts with $',1
End
End Try
Begin Catch
Throw;
End Catch
End Try
Begin Catch
Select ERROR_MESSAGE() As Error
End Catch
Output:
Reference: http://msdn.microsoft.com/en-us/library/ee677615
If you liked this post, do like on Facebook at https://www.facebook.com/s4sql
2 Comments »
Leave a Reply
-
Archives
- March 2013 (1)
- January 2013 (3)
- December 2012 (2)
- November 2012 (1)
- August 2012 (4)
- July 2012 (2)
- June 2012 (2)
- May 2012 (1)
- April 2012 (5)
- March 2012 (1)
- February 2012 (1)
- January 2012 (5)
-
Categories
-
RSS
Entries RSS
Comments RSS


You may find my post on RAISERROR v/s THROW interesting: http://beyondrelational.com/modules/2/blogs/77/posts/11287/sunset-for-raiserror-and-sunrise-for-throw-sql-11-denali.aspx.
Thank you Nakul for reading my blog and sharing the link.