Server Interaction  «Prev  Next»
Lesson 5 Detecting and reporting errors
Objective Handle errors in your Transact-SQL code

Detecting and Reporting SQL Server Errors

An error is the result of a Transact-SQL statement that does not execute successfully. Errors come from a wide range of causes: invalid syntax, invalid object names, data type mismatches, and key violations among them, and they can occur at any time, often through no fault of the programmer. A table renamed by someone else, a column dropped during a deployment, or a constraint added after your code was written can all "break" a statement that worked perfectly the day before. Handling errors well means detecting that something went wrong, reporting enough detail to diagnose it, and deciding what the calling code should do next: retry, roll back, log, or simply notify the user.
In SQL Server 2025, the primary mechanism for all three of those tasks is the TRY...CATCH construct. This lesson builds TRY...CATCH from the ground up, covers the legacy @@ERROR approach it replaced for continuity with the previous lesson, and closes with the functions and statements you use once an error has been caught.

Detecting Errors with TRY...CATCH

A TRY...CATCH block wraps the statements that might fail in BEGIN TRY ... END TRY, immediately followed by BEGIN CATCH ... END CATCH. If any statement inside the TRY block raises an error that TRY...CATCH can intercept, control passes immediately to the first statement inside the matching CATCH block; nothing after the failing statement inside TRY runs.


BEGIN TRY
    UPDATE dbo.employees
    SET Phone = '555-1212'
    WHERE EmployeeID = 17;
END TRY
BEGIN CATCH
    SELECT 'Error Occurred!' AS Message;
END CATCH;

TRY...CATCH intercepts execution errors with a severity greater than 10 that do not terminate the database connection. It does not catch:
  • Informational messages or warnings (severity 10 or lower)
  • Fatal errors (severity 20 or higher) that close the connection outright
  • Client-side timeouts or a KILL command issued against the session
  • A compile-time error, such as a syntax mistake, in the same batch
  • A deferred-name-resolution error, such as referencing a table or column that does not exist, occurring in the same scope as the TRY block
That last exception has an important twist worth remembering: if the same kind of error happens inside a stored procedure that is itself called from within an outer TRY block, the outer CATCH does catch it, even though a TRY...CATCH written inside the stored procedure's own body would not catch it. SQL Server defers resolving object names inside a stored procedure until the procedure actually runs, so from the caller's point of view the missing-object error surfaces as an ordinary runtime error, which the outer CATCH handles normally.

SET XACT_ABORT ON

Add SET XACT_ABORT ON; near the top of any stored procedure or batch that modifies data and opens a transaction. With it on, a runtime error automatically dooms and fully rolls back the current transaction rather than leaving it open in an uncertain state; without it, some errors leave the transaction active, and a careless CATCH block that forgets to check can end up committing partial work.


CREATE OR ALTER PROCEDURE dbo.UpdateEmployeePhone
    @EmployeeID int,
    @Phone varchar(20)
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    UPDATE dbo.employees
    SET Phone = @Phone
    WHERE EmployeeID = @EmployeeID;
END;

The Legacy Approach: Testing @@ERROR

Before TRY...CATCH was introduced, the only way to detect an error was to test the @@ERROR system function immediately after the Transact-SQL statement in question, a mechanism the previous lesson already covered as a legacy, superseded function. @@ERROR equals zero if no error occurred on the statement just executed, or an error number if one did, but it resets with every statement, so it has to be captured into a variable or tested right away.


UPDATE dbo.employees
SET Phone = '555-1212'
WHERE EmployeeID = 17;

IF @@error <> 0
    SELECT 'Error Occurred!' AS Message;

The same pattern extends to checking for a specific, known error number. Error 547, for example, signals a foreign key or check constraint violation:


UPDATE dbo.employees
SET DepartmentID = @Dept
WHERE DepartmentID = 101;

IF @@error = 547
    SELECT 'Department number ' + CAST(@Dept AS varchar) + ' does not exist' AS Message;

The underlying idea, reacting differently to a specific error number, carries over directly into TRY...CATCH; only the detection mechanism changes, from checking @@ERROR immediately after the fact to catching the error and checking ERROR_NUMBER() inside the CATCH block:


BEGIN TRY
    UPDATE dbo.employees
    SET DepartmentID = @Dept
    WHERE DepartmentID = 101;
END TRY
BEGIN CATCH
    IF ERROR_NUMBER() = 547
        SELECT 'Department number ' + CAST(@Dept AS varchar) + ' does not exist' AS Message;
    ELSE
        THROW;
END CATCH;

TRY...CATCH has two practical advantages over the @@ERROR pattern: a single CATCH block covers every statement inside its TRY block, instead of needing a check after each one, and the error functions covered next remain available throughout the entire CATCH block rather than only immediately after the failing statement.

Reporting and Inspecting Errors: the ERROR_*() Functions

Inside a CATCH block, a set of error functions reports on the failure that just occurred. Each one returns NULL if called outside a CATCH block, and each keeps returning the same values throughout the block, even across nested procedure calls:
FunctionReturns
ERROR_NUMBER()The error number
ERROR_SEVERITY()The severity level
ERROR_STATE()The error state number
ERROR_PROCEDURE()The stored procedure or trigger where the error occurred, or NULL if the error did not occur inside one
ERROR_LINE()The line number inside the routine or batch that raised the error
ERROR_MESSAGE()The full error text, with any parameters already substituted in


BEGIN TRY
    UPDATE dbo.employees
    SET DepartmentID = @Dept
    WHERE DepartmentID = 101;
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;

Reporting Errors to the Caller: THROW

To send an error back to whatever called the current batch or procedure, SQL Server 2025 favors the THROW statement over the older RAISERROR statement. THROW with no arguments, used inside a CATCH block, re-throws the exact error that was caught, preserving its original number, severity, state, procedure name, and line number rather than reporting them as if they came from the line containing THROW itself:


BEGIN TRY
    UPDATE dbo.employees
    SET DepartmentID = @Dept
    WHERE DepartmentID = 101;
END TRY
BEGIN CATCH
    THROW;
END CATCH;

THROW <error_number>, '<message>', <state>; raises a custom error instead, with an error number of 50000 or higher reserved for user-defined errors. One syntax quirk is easy to trip over: the statement immediately before a stand-alone THROW must end with a semicolon, or SQL Server raises a parsing error rather than running the THROW you intended.


IF NOT EXISTS (SELECT 1 FROM dbo.departments WHERE DepartmentID = @Dept)
BEGIN
    THROW 50001, 'Department does not exist.', 1;
END

Handling the Transaction: XACT_STATE()

Entering a CATCH block does not automatically roll back a transaction that is still open; the CATCH block itself has to decide what to do with it. The XACT_STATE() function reports what state the current transaction is in:
ValueMeaning
1An active, committable transaction
-1An active but uncommittable (doomed) transaction, which can only be fully rolled back, never committed or partially rolled back to a savepoint
0No transaction is currently active

A transaction becomes doomed when SET XACT_ABORT ON is in effect and a runtime error occurs inside it; checking XACT_STATE() before issuing a ROLLBACK or COMMIT avoids an attempt to commit or partially roll back a transaction that SQL Server has already marked uncommittable.

Looking Up Error Text: sys.messages

Every system error number and its description are stored in the sys.messages catalog view. An older system table, sysmessages (sometimes referenced as master.dbo.sysmessages), still exists today only as a deprecated SQL Server 2000-era compatibility view, and Microsoft's own documentation advises against using it in new development. Query sys.messages instead:


SELECT
    message_id AS ErrorNumber,
    severity AS Severity,
    is_event_logged AS IsEventLogged,
    [text] AS MessageText
FROM sys.messages
WHERE language_id = 1033
  AND message_id < 50000
ORDER BY message_id;

Filtering to message_id < 50000 limits the results to SQL Server's own built-in messages; error numbers 50000 and above are reserved for messages your own code raises with THROW or adds with sp_addmessage.

Nesting TRY...CATCH and Rethrowing

A CATCH block can contain its own TRY...CATCH, which is useful when the error-handling code itself might fail, such as when logging to a table that could be unavailable. A common, robust pattern wraps the logging attempt in its own nested block so a logging failure does not mask or replace the original error:


BEGIN TRY
    -- statements that might fail
    UPDATE dbo.employees
    SET DepartmentID = @Dept
    WHERE DepartmentID = 101;
END TRY
BEGIN CATCH
    DECLARE @OriginalMessage nvarchar(2048) = ERROR_MESSAGE();
    DECLARE @OriginalNumber int = ERROR_NUMBER();

    BEGIN TRY
        INSERT INTO dbo.ErrorLog (ErrorNumber, ErrorMessage, LoggedAtUtc)
        VALUES (@OriginalNumber, @OriginalMessage, SYSUTCDATETIME());
    END TRY
    BEGIN CATCH
        -- Logging failed; proceed without it rather than losing the original error.
    END CATCH;

    THROW;
END CATCH;

Note that THROW with no arguments must run from inside the CATCH block where the original error was caught; once execution leaves that CATCH block, the original error information is gone, and a parameterless THROW elsewhere raises its own error instead.

Error Handling and SQL Server 2025's Newer T-SQL Features

The functions introduced in SQL Server 2025, covered in earlier lessons for their query and variable usage, follow the same TRY...CATCH rules as any other statement, but each has its own error-prone edge worth wrapping deliberately.

Recursive WITH (CTE) Queries

A recursive common table expression built with WITH has a server-wide default limit of 100 recursive executions, controlled by the MAXRECURSION query hint. Exceed it without raising the limit, and SQL Server raises error 530 and terminates the statement rather than returning a partial result silently:


BEGIN TRY
    WITH OrgChart AS (
        SELECT EmployeeID, ManagerID, 0 AS Depth
        FROM dbo.employees
        WHERE ManagerID IS NULL
        UNION ALL
        SELECT e.EmployeeID, e.ManagerID, o.Depth + 1
        FROM dbo.employees AS e
        INNER JOIN OrgChart AS o ON e.ManagerID = o.EmployeeID
    )
    SELECT * FROM OrgChart OPTION (MAXRECURSION 50);
END TRY
BEGIN CATCH
    IF ERROR_NUMBER() = 530
        SELECT 'Recursion limit exceeded; check for a cycle in the data.' AS Message;
    ELSE
        THROW;
END CATCH;

A recursion-limit error almost always points to a cycle in the underlying data, such as a manager mistakenly recorded as their own report, rather than to a problem with the query itself.

VECTOR and VECTOR_DISTANCE

VECTOR_DISTANCE(distance_metric, vector1, vector2) returns an error if the metric name is not valid or if either argument is not actually the vector data type, and comparing or converting between vectors of mismatched dimensions raises its own dimension-mismatch error rather than returning an approximate result:


DECLARE @Query AS VECTOR(1536);
BEGIN TRY
    SELECT TOP (5) ProductID,
           VECTOR_DISTANCE('cosine', ProductEmbedding, @Query) AS Distance
    FROM dbo.Products
    ORDER BY Distance;
END TRY
BEGIN CATCH
    SELECT 'Embedding comparison failed: ' + ERROR_MESSAGE() AS Message;
END CATCH;

Dimension mismatches are typically a data-entry problem: an embedding generated by a different model, or a column holding a mixture of embedding sizes from a model that was changed partway through loading the table.

REGEXP and JSON Functions

REGEXP_LIKE and the related REGEXP_* functions raise an error for a malformed regular-expression pattern, so validating user-supplied patterns inside a TRY block is worthwhile before relying on them in a WHERE clause. JSON_VALUE behaves differently: given a path that does not exist in the JSON, it returns NULL rather than raising an error, but given text that is not valid JSON at all under the native json type's stricter validation, the error surfaces at the point the value is stored or cast, not at the point it is queried. Catching that conversion error early, rather than only when a report later tries to read the column, keeps a bad JSON payload from silently becoming an unreadable row.


BEGIN TRY
    DECLARE @Payload json = '{"status": "active", "tier": 2';  -- missing closing brace
    INSERT INTO dbo.Settings (SettingsJson) VALUES (@Payload);
END TRY
BEGIN CATCH
    SELECT 'Invalid JSON payload: ' + ERROR_MESSAGE() AS Message;
END CATCH;

A Few More Things to Watch For

A Complete Pattern

Putting detection, reporting, and transaction handling together, a production-style procedure rolls back any open transaction before logging the error, so the rollback does not erase the log entry, then re-throws so the caller is notified:


CREATE OR ALTER PROCEDURE dbo.TransferDepartmentBudget
    @FromDept int,
    @ToDept int,
    @Amount money
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    BEGIN TRY
        BEGIN TRANSACTION;

        UPDATE dbo.departments SET Budget = Budget - @Amount WHERE DepartmentID = @FromDept;
        UPDATE dbo.departments SET Budget = Budget + @Amount WHERE DepartmentID = @ToDept;

        COMMIT TRANSACTION;
    END TRY
    BEGIN CATCH
        IF XACT_STATE() <> 0
            ROLLBACK TRANSACTION;

        INSERT INTO dbo.ErrorLog (ErrorNumber, ErrorMessage, LoggedAtUtc)
        VALUES (ERROR_NUMBER(), ERROR_MESSAGE(), SYSUTCDATETIME());

        THROW;
    END CATCH;
END;

Walking through what happens if the second UPDATE fails: SET XACT_ABORT ON dooms the transaction the moment the error occurs, control jumps to the CATCH block, XACT_STATE() confirms a transaction is still open so it gets rolled back, the error is logged with its original number and message intact, and THROW sends that same error back to whatever called the procedure, whether that is an application, a script, or another stored procedure with its own TRY...CATCH around the call.

What's Ahead

Detecting and reporting an error is only half the picture. The next lesson turns to raising errors deliberately, building on THROW and the custom error numbers introduced here to look at writing your own error conditions into a procedure's logic rather than only reacting to errors SQL Server raises on its own.

SEMrush Software 5 SEMrush Banner 5