Exception Handling in SQL Server by TRY…CATCH
Like C#, SQL Server also has an exception model to handle exceptions and errors that occurs in T-SQL statements. To handle exception in Sql Server we have TRY..CATCH blocks. We put T-SQL statements in TRY block and to handle exception we write code in CATCH block. If there is an error in code within TRY block then the control will automatically jump to the corresponding CATCH blocks. In Sql Server, against a Try block, we can have only one CATCH block.
BEGIN TRY --T-SQL statements --or T-SQL statement blocks END TRY BEGIN CATCH --T-SQL statements --or T-SQL statement blocks END CATCH
Error Functions used within CATCH block
This returns the error number and its value is the same as for @@ERROR function.
This returns the line number of T-SQL statement that caused an error.
This returns the severity level of the error.
This returns the state number of the error.
This returns the name of the stored procedure or trigger where the error occurred.
This returns the full text of error message. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times.
Exception handling example
BEGIN TRY DECLARE @num INT, @msg varchar(200) ---- Divide by zero to generate Error SET @num = 5/0 PRINT 'This will not execute' END TRY BEGIN CATCH PRINT 'Error occured that is' set @msg=(SELECT ERROR_MESSAGE()) print @msg; END CATCH GO
BEGIN TRY DECLARE @num INT ---- Divide by zero to generate Error SET @num = 5/0 PRINT 'This will not execute' END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage; END CATCH; GO
A TRY..CATCH block combination catches all the errors that have a severity between 11 and 19.
The CATCH block is executed only if there is an error occurs in T-SQL statements within TRY block otherwise the CATCH block is ignored.
Each TRY block is associated with only one CATCH block and vice versa
TRY and CATCH blocks can’t be separated with the GO statement. We need to put both TRY and CATCH blocks within the same batch.
TRY..CATCH blocks can be used with transactions. We check the number of open transactions by using @@TRANCOUNT function in Sql Server.
XACT_STATE function within the TRY..CATCH block can be used to check whether an open transaction is committed or not. It will return -1 if the transaction is not committed else returns 1.
Read More Articles Related to SQL Server
In this article, I try to explain Exception handling in Sql Server with example. I hope after reading this article you will be know how to handle exception in Sql Server. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.
Take our free skill tests to evaluate your skill!
In less than 5 minutes, with our skill test, you can identify your knowledge gaps and strengths.