Like other programming language, Microosft SQL Server also has an error handling model to handle exceptions and errors that occurs in T-SQL statements. We have TRY..CATCH blocks to handle exception/error in Sql Server. 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. 

Basic Syntax of TRY..CATCH of Microsoft SQL Server

Example of using TRY..CATCH

Error Functions used within CATCH block
  1. ERROR_NUMBER(): This returns the error number and its value is the same as for @@ERROR function.
  2. ERROR_LINE(): This returns the line number of T-SQL statement that caused an error.
  3. ERROR_SEVERITY(): This returns the severity level of the error.
  4. ERROR_STATE(): This returns the state number of the error.
  5. ERROR_PROCEDURE(): This returns the name of the stored procedure or trigger where the error occurred.
  6. ERROR_MESSAGE(): 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.
  1. A TRY..CATCH block combination catches all the errors that have a severity between 11 and 19.
  2. 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.
  3. Each TRY block is associated with only one CATCH block and vice versa.
  4. 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.
  5. TRY..CATCH blocks can be used with transactions. We check the number of open transactions by using @@TRANCOUNT function in Sql Server.
  6. 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.
Implement error handling in SQL Server

The article was published on March 6, 2023 @ 11:14 AM

Leave a Comment