T-SQL Tutorial

Handle Exceptions


Handling exceptions in SQL Server is crucial for managing errors and ensuring the robustness of your database applications. SQL Server provides various mechanisms and best practices for handling exceptions effectively. In this article, we will explore how to handle exceptions in SQL Server using Try...Catch blocks, error functions, and custom error messages.


How to Handle exceptions in SQL Server?

In SQL Server, exceptions can be handled using the TRY...CATCH block. The TRY block is used to enclose the code that may cause an exception, and the CATCH block is used to handle the exception.


Try...Catch Blocks

Try...Catch blocks are used to handle exceptions in SQL Server. They allow you to enclose a block of code that might raise an exception within a Try block and then specify how to handle the exception in a Catch block. Here's a basic structure:

BEGIN TRY
-- -- Your SQL statements here
--END TRY
--BEGIN CATCH
-- -- Handle the exception here
--END CATCH

TRY Block: Inside the Try block, you place the code that might cause an exception.
CATCH Block: Inside the Catch block, you specify the actions to take when an exception occurs. This can include logging the error, rolling back transactions, or providing a user-friendly error message.


Example

Here is an example of how to handle an exception in SQL Server:

BEGIN TRY
-- code that may cause an exception
SELECT 1/0
END TRY
BEGIN CATCH
-- code to handle the exception
PRINT 'An error occurred: ' + ERROR_MESSAGE()
END CATCH;

In this example, the code in the TRY block attempts to divide 1 by 0, which will cause a divide-by-zero exception. The code in the CATCH block will then be executed, and the error message will be printed with function ERROR_MESSAGE.

You can also retrieve information about the error using the ERROR_NUMBER and ERROR_LINE functions, which return the error number and line number where the error occurred, respectively.






Error Functions

SQL Server provides various functions to access error information within the Catch block:
ERROR_MESSAGE(): Returns the error message text.
ERROR_NUMBER(): Returns the error number.
ERROR_SEVERITY(): Returns the severity level of the error.
ERROR_STATE(): Returns the state number of the error.

Example:

BEGIN CATCH
-- Handle the exception
PRINT 'Error Number: ' + CAST(ERROR_NUMBER() AS NVARCHAR(10))
PRINT 'Error Message: ' + ERROR_MESSAGE()
END CATCH


Custom Error Messages

You can also raise custom errors using the THROW statement. This allows you to provide more meaningful error messages to users or log specific information about the error.

Example:

BEGIN TRY
-- Attempt to divide by zero
DECLARE @result INT = 10 / 0
END TRY
BEGIN CATCH
-- Handle the exception and raise a custom error
THROW 50000, 'Division by zero error', 1
END CATCH

In the above example, we raise a custom error with a custom error number (50000), a custom error message ('Division by zero error'), and a state (1).

Handling exceptions in SQL Server helps maintain the integrity and reliability of your database applications. By using Try...Catch blocks, error functions, and custom error messages, you can gracefully manage errors, log information for troubleshooting, and provide a better user experience.

It's also a good practice to use a transaction when doing the operation that may cause the exception, so that you can rollback the transaction in case of exception, this way the data will not be in an invalid state. In addition, you can use the RAISERROR statement to raise a user-defined error, this way you can customize the error message and handle it accordingly.