Consider the following example
SELECT ROUND(800.0, -3)
On executing this statement, you get the following error:
because the value does not fit into the decimal data type.
You can use @@RAISERROR to raise a message
BEGIN TRY
SELECT ROUND(800.0, -3)
END TRY
BEGIN CATCH
DECLARE @ErrorMsg nvarchar(1000), @Severity int
SELECT @ErrorMsg = ERROR_MESSAGE(),
@Severity = ERROR_SEVERITY()
RAISERROR (@ErrorMsg, @Severity, 1)
END CATCH
Note: The old syntax of RAISERROR syntax specifying the error number and message number got deprecated (RAISEERROR 50005 ‘Exception Occurred’). Instead the new syntax RAISEERROR(50005, 10, 1) allowed you to specify the messageid, severity and state). For new applications use THROW.
However in SQL Server 2012, there’s a better way to this without much efforts – THROW. Consider the following code
BEGIN TRY
SELECT ROUND(800.0, -3)
END TRY
BEGIN CATCH
THROW
END CATCH
As you can see, with just one word THROW, we were able to handle the error with grace and get a result too.
2 comments:
Excellent Explanation
Isn't the example THROW pointless? It doesn't do anything with the caught error or provide any extra information in the throw, so it's a no-op.
Post a Comment