SQL Server · Reliability & Concurrency

Error Handling with TRY...CATCH

When one statement in a transaction fails, the whole unit of work must be undone. TRY…CATCH and XACT_ABORT make that reliable.

Advanced 5 min Lesson 36 of 44Examples run on SQL Server 2022 and Azure SQL Database.
0/44 in SQL Server
On this page · 5 min · Advanced

Learning objectives#

  • Wrap work in TRY...CATCH
  • Roll back correctly with XACT_STATE
  • Re-raise errors with THROW
  • Log error details

Explanation#

Put the transaction inside BEGIN TRY … END TRY. If any statement raises an error, control jumps to BEGIN CATCH, where ERROR_NUMBER(), ERROR_MESSAGE(), ERROR_LINE() and ERROR_PROCEDURE() describe it.

In the CATCH block, roll back if a transaction is open (IF XACT_STATE() <> 0 ROLLBACK), optionally log the error, then THROW; to re-raise it so the caller (your app) knows the operation failed.

SET XACT_ABORT ON at the top of procedures makes SQL Server roll back the whole transaction on most run-time errors, including when the client times out — without it, a timeout can leave a transaction open and locks held.

Use THROW 50001, N'message', 1; to raise your own business errors (numbers 50000 and above).

Step-by-step screens#

Drawings of SQL Server 2022 Setup and SQL Server Management Studio (SSMS 20) with the ShopDB sample database. The red numbers match the numbered actions under each picture; names on your computer will differ.

Loading pictures…

Code example: Place an order safely#

SQLPlace an order safely Illustrative
CREATE OR ALTER PROCEDURE dbo.PlaceOrder @CustomerId INT, @ProductId INT, @Qty INT
AS
BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;
    BEGIN TRY
        BEGIN TRANSACTION;


        UPDATE Products SET Stock = Stock - @Qty
        WHERE ProductId = @ProductId AND Stock >= @Qty;
        IF @@ROWCOUNT = 0 THROW 50001, N'Not enough stock.', 1;


        INSERT Orders (CustomerId, OrderDate, Status) VALUES (@CustomerId, SYSDATETIME(), 'New');
        INSERT OrderItems (OrderId, ProductId, Quantity, UnitPrice)
        SELECT SCOPE_IDENTITY(), @ProductId, @Qty, Price FROM Products WHERE ProductId = @ProductId;


        COMMIT;
    END TRY
    BEGIN CATCH
        IF XACT_STATE() <> 0 ROLLBACK;
        INSERT dbo.ErrorLog (Number, Message, ProcName, Line, LoggedAt)
        VALUES (ERROR_NUMBER(), ERROR_MESSAGE(), ERROR_PROCEDURE(), ERROR_LINE(), SYSDATETIME());
        THROW;
    END CATCH
END;
Expected output
EXEC dbo.PlaceOrder 1, 3, 500;
Msg 50001, Level 16, State 1, Procedure dbo.PlaceOrder, Line 13
Not enough stock.
-- No order row was created; the stock was not changed; ErrorLog has one row.

This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.

Step-by-step explanation#

  1. XACT_ABORT ON makes errors (and client time-outs) roll back.
  2. The stock update succeeds only if enough stock exists.
  3. THROW 50001 raises a business error when it didn’t.
  4. CATCH rolls back, logs the details, and re-throws.
  5. The app receives the error and can show “Not enough stock”.

Real-world use case#

An order procedure called by a busy web API never leaves stock reduced without an order, even when the API times out halfway through.

Common mistakes#

Swallowing the error

A CATCH block without THROW makes the app think the order succeeded.

Logging before rollback

The log row is inside the failed transaction and gets rolled back too. Roll back first, then log.

Best practices#

  • SET XACT_ABORT ON in procedures
  • IF XACT_STATE() <> 0 ROLLBACK
  • Log, then THROW
  • Use 50000+ numbers for business errors

Remember this#

TRY → CATCH → ROLLBACK → THROW.

XACT_ABORT ON.

ERROR_MESSAGE() etc. only inside CATCH.

Practice exercise#

Your task: Raise a custom error 50010 with the message “Invalid quantity”.

Show solution
SQL Illustrative
THROW 50010, N'Invalid quantity', 1;

Mini quiz#

Error Handling with TRY...CATCH quizMultiple choice Question 1 of 1

Why use SET XACT_ABORT ON?

Score so far: 0/0

Want more? Practise all SQL Server MCQs · SQL Server interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.