Error Handling (Transact-SQL)

This topic provides information about error handling in Transact-SQL (T-SQL). Effective error handling is crucial for building robust and reliable database applications. T-SQL offers several mechanisms to detect, report, and manage errors that occur during the execution of your scripts and stored procedures.

Understanding Errors in T-SQL

Errors in T-SQL can be categorized as:

Mechanisms for Error Handling

1. @@ERROR System Function (Legacy)

The @@ERROR global variable returns the error number of the last Transact-SQL statement executed. A return value of 0 indicates that the statement executed successfully. A non-zero value indicates an error.

Note: While @@ERROR is still supported for backward compatibility, it is recommended to use the TRY...CATCH construct for new development, as it provides more robust and structured error handling.

IF @@ERROR <> 0
BEGIN
    -- Handle the error here
    PRINT 'An error occurred!'
END

2. RAISERROR Statement

The RAISERROR statement is used to generate custom error messages and return them to the client application. You can define your own error numbers and severity levels.

RAISERROR ('User-defined error message.', 16, 1) WITH LOG

Parameters:

3. TRY...CATCH Construct (Recommended)

The TRY...CATCH construct provides a structured way to handle errors in T-SQL. The code that might cause an error is placed within the TRY block. If an error occurs within the TRY block, execution immediately transfers to the CATCH block.

BEGIN TRY
    -- Code that might raise an error
    SELECT 1 / 0
END TRY
BEGIN CATCH
    -- Error handling code
    PRINT 'An error occurred in the TRY block.'
    PRINT 'Error Number: ' + CAST(ERROR_NUMBER() AS VARCHAR(10))
    PRINT 'Error Message: ' + ERROR_MESSAGE()
    PRINT 'Error Severity: ' + CAST(ERROR_SEVERITY() AS VARCHAR(10))
    PRINT 'Error State: ' + CAST(ERROR_STATE() AS VARCHAR(10))
    PRINT 'Error Procedure: ' + ISNULL(ERROR_PROCEDURE(), '(Not from a stored procedure)')
    PRINT 'Error Line: ' + CAST(ERROR_LINE() AS VARCHAR(10))

    -- Optionally, re-raise the error or return a custom error
    -- RAISERROR('Custom error message for the caller.', 16, 1)
END CATCH

Within the CATCH block, you can use the following error-handling functions:

Best Practices for Error Handling

Note: The TRY...CATCH construct is available in SQL Server 2005 and later versions.
Tip: For critical operations, consider using transactions in conjunction with error handling to ensure data integrity. If an error occurs within a transaction, you can roll back the transaction to maintain a consistent database state.
Important: Errors with severity levels 19 through 25 will terminate the connection, even within a CATCH block. Handle these errors with extreme caution.