07
DecException Handling in SQL Server by TRY…CATCH
Exception Handling in SQL Server: An Overview
SQL Server also provides an exception-handling mechanism like any other programming language like C#, C++, Java, C, etc. It has built-in support for constructs like TRY, and CATCH that can handle errors elegantly. In this SQL Server tutorial, we will understand how to handle errors in SQL Server using TRY...CATCH statements.
To move forward you must know what exceptions are and their type in SQL Server. If you aren't aware, refer to SQL Server Exceptions Working.
Read More: Basics of SQL Commands
TRY...CATCH Construct in SQL Server
To handle exceptions in Sql Server we have TRY...CATCH blocks. We need to put the T-SQL statements that could cause an exception in the TRY block and a CATCH block immediately after it. If there is an error in code within the TRY block, the control will automatically jump to the corresponding CATCH blocks. A TRY...CATCH construct cannot span multiple blocks of Transact-SQL statements.
TRY...CATCH Syntax
BEGIN TRY
--T-SQL statements
--or T-SQL statement blocks
END TRY
BEGIN CATCH
--T-SQL statements
--or T-SQL statement blocks
END CATCH
Read More: SQL Server Interview Questions and Answers
How does TRY...CATCH helps in Handling Errors and Exceptions.
In the above syntax code,
- The exception-causing SQL statements are in the BEGIN TRY block.
- If any exception arises, the control is immediately transferred to the BEGIN CATCH block.
- In the BEGIN CATCH block, there are statements to be executed if an exception occurs in the BEGIN TRY block. In other words, the statements inside the BEGIN CATCH block are used for handling the program flow in case the exception gets triggered.
- If no exception arises i.e. all the SQL statements inside the BEGIN TRY block are executed, the control is not transferred to the BEGIN CATCH block.
Read More - Top 50 DBMS Interview Questions and Answers
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 the 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 the 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
Output
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
Output
Note
- A TRY..CATCH block combination catches all the errors having a severity between 11 and 19.
- The CATCH block is executed only if there is an error that occurs in T-SQL statements within the 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 from 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 the @@TRANCOUNT function in SQL Server.
- XACT_STATE function within the TRY...CATCH block can be used to check whether an open transaction is committed. It will return -1 if the transaction is not committed else will return 1.
Techniques for testing and debugging TRY...CATCH blocks
- Deliberate Error Induction: Intentionally induce errors within the TRY block to trigger the CATCH block's execution path.
- PRINT Statements: Use PRINT statements within the TRY and CATCH blocks to output messages indicating the execution flow.
- Error Information Views: Examine error information by querying system views such as sys.messages and retrieve specific error details using functions like ERROR_MESSAGE().
- SQL Server Management Studio (SSMS) Debugging: Utilize SSMS debugging features such as breakpoints, stepping through code, and inspecting variable values to troubleshoot TRY...CATCH blocks effectively.
Best Practices for Implementing TRY...CATCH in SQL Server
- Use for Error Handling: Apply TRY...CATCH blocks primarily for error handling and gracefully managing exceptions in SQL Server code.
- Keep Scope Limited: Limit the scope of TRY...CATCH blocks to the smallest possible section of code where errors might occur.
- Capture Relevant Error Information: Capture relevant error information within the CATCH block using functions like ERROR_MESSAGE(), ERROR_NUMBER(), ERROR_STATE(), ERROR_PROCEDURE(), and ERROR_LINE().
- Use RAISEERROR() or THROW: Raise custom errors within the CATCH block using the RAISEERROR() or THROW statements to provide informative error messages and control error severity.
- Handle Specific Errors: Handle specific error conditions separately within the CATCH block.
- Rollback Transactions: Rollback open transactions within the CATCH block to maintain data consistency and integrity in case of errors.
- Logging and Alerting: Implement logging mechanisms to record error details in a log table or file for later analysis, and configure alerts to notify administrators of critical errors.
- Test and Validate: Thoroughly test and validate the error-handling logic by intentionally inducing errors and verifying the behavior of the TRY...CATCH blocks in various scenarios.
- Keep CATCH Blocks Lightweight: Keep the CATCH blocks lightweight by avoiding complex logic and expensive operations to ensure minimal impact on performance.
Summary
In this article, I have tried to explain Exception handling in SQL Server with examples. I hope after reading this article you will know how to handle exceptions in SQL Server. If you want to gain a practical understanding, you can enroll in our SQL Server Course.
Do you Know?
.NET is gaining popularity day by day, especially after the release of .NET 8. .NET 8 is not only a framework version but much more than that. It redefines the way software applications are built and deployed, enabling developers to meet the evolving demands of modern computing.
Therefore, if you want to upskill yourselves and stand out from others consider our following training programs on .NET.
- .NET Developer Training With Certification
- ASP.NET Core Certification Training
- ASP.NET Core Course
- .NET Solution Architect Certification Training
- Full-Stack .NET Developer Certification Training Program
- Advanced Full-Stack .NET Developer Certification Training
FAQs
- User-Defined Exceptions
- System Exceptions
- RAISERROR Exceptions
DECLARE @result FLOAT;
SET @result = 10 / 0; -- Division by zero error
END TRY
BEGIN CATCH
SELECT 'Error occurred: ' + ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
Take our Sqlserver skill challenge to evaluate yourself!
In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.