In SQL Server, how should a TRY...CATCH block roll back a failed transaction, and why pair THROW with XACT_ABORT and XACT_STATE?
answer
- statement rollback versus transaction rollback
- the default is OFF outside triggers
- minus one means doomed
- rethrow without arguments
- timeouts never reach CATCH
basics
~20 sRun SET XACT_ABORT ON, open the transaction inside BEGIN TRY, and in BEGIN CATCH roll back when XACT_STATE() <> 0, then THROW; to re-raise the original error. XACT_ABORT stops half-committed work, and XACT_STATE detects a doomed transaction.
solid answer
~40 sWith `SET XACT_ABORT OFF`, the default outside triggers, many run-time errors such as a constraint violation roll back **only the failing statement** and leave the transaction open, so code that carries on can commit half the work. `SET XACT_ABORT ON` makes a run-time error terminate and roll back the whole transaction, and it also covers a client timeout, which raises an attention that no `CATCH` block ever sees. Inside `TRY`, an error that would end the transaction instead makes it **uncommittable**: `XACT_STATE()` returns `-1`, and the session may only read or issue a full `ROLLBACK`. So the `CATCH` block runs `IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;` and then a bare `THROW;`, which re-raises the original error number and severity. `RAISERROR` reports error 50000 when given a message string and does not honour `XACT_ABORT`.
code
sql · 15 linesSET XACT_ABORT ON;
DECLARE @from int = 1, @to int = 2, @amount decimal(12, 2) = 50.00;
BEGIN TRY
BEGIN TRANSACTION;
UPDATE dbo.accounts SET balance = balance - @amount WHERE account_id = @from;
UPDATE dbo.accounts SET balance = balance + @amount WHERE account_id = @to;
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0
ROLLBACK TRANSACTION;
THROW;
END CATCH;go deeper
Recall the TRY...CATCH syntax, the ERROR_ functions available in CATCH, and that a failed statement does not by itself roll back its transaction.
Explain what XACT_ABORT changes, what an uncommittable transaction is, and why the CATCH block checks XACT_STATE() before rolling back and rethrowing.
Show the production view: orphaned transactions from client timeouts, Msg 3930 from logging before rollback, and RAISERROR rethrows that hide the original error number.
Argue for a house template: XACT_ABORT ON plus a fixed CATCH block in every write procedure, so error handling is reviewed once and not per author.
## What goes wrong without a pattern SQL Server does not automatically roll back a transaction just because a statement in it failed. With **`SET XACT_ABORT OFF`**, which is the default for ordinary T-SQL (triggers default to `ON`), many run-time errors roll back **only the statement that raised them**. A foreign key violation in the second of three `UPDATE`s leaves the first and third in an open transaction, and a later `COMMIT` makes that partial work permanent. Depending on the error's severity the whole transaction may still be rolled back, so you cannot even rely on one behaviour. ## The building blocks - **`BEGIN TRY ... END TRY BEGIN CATCH ... END CATCH`** catches execution errors with severity above 10 that do not close the connection. Inside `CATCH`, `ERROR_NUMBER()`, `ERROR_MESSAGE()`, `ERROR_SEVERITY()`, `ERROR_STATE()`, `ERROR_LINE()` and `ERROR_PROCEDURE()` describe the error. - **`SET XACT_ABORT ON`**: a run-time error terminates and rolls back the entire transaction. - **`XACT_STATE()`** returns `1` (an active, committable transaction), `0` (no transaction) or `-1` (an active but **uncommittable** transaction). - **`THROW`**: with no arguments, inside a `CATCH` block, it re-raises the caught error; with arguments, `THROW 50001, N'message', 1;` raises a new error whose number must be at least 50,000 and whose severity is always 16. ## Uncommittable transactions An error that would end a transaction outside a `TRY` block puts it into the **uncommittable** state when it happens inside one, so that your `CATCH` block still runs. In that state the session can only read and issue a **full** `ROLLBACK TRANSACTION`: no writes, no `COMMIT`, and no rollback to a savepoint. Trying to write gives **Msg 3930**, "The current transaction cannot be committed and cannot support operations that write to the log file. Roll back the transaction." If the batch ends with the transaction still uncommittable, the engine rolls it back and, if no error was sent when it became uncommittable, sends one to the client. `@@TRANCOUNT` cannot tell you whether a transaction is uncommittable, which is why the `CATCH` block tests `XACT_STATE()`. When it returns `1` the transaction is still committable, and you choose whether to commit the work done before the error or roll it back; most code rolls back. ## The canonical pattern 1. `SET XACT_ABORT ON;` at the top of the batch or procedure. 2. `BEGIN TRY`, then `BEGIN TRANSACTION`, the work, and `COMMIT TRANSACTION`. 3. In `BEGIN CATCH`, `IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;`. 4. Then `THROW;` so the caller sees the real error. The statement before `THROW` must end with a semicolon. Logging fits between steps 3 and 4: after the rollback, the session can write again, so an `INSERT` into an error table succeeds there and not before. ## THROW versus RAISERROR | | `THROW` | `RAISERROR` | |---|---|---| | Re-raise the caught error | `THROW;` keeps the original number and severity | only rebuilds it; with a message string the number becomes 50000 | | Severity | 16 for a new error; original when rethrowing | you pass it; 10 or lower does not enter `CATCH` | | Message number | need not exist in `sys.messages` | a `msg_id` must exist in `sys.messages` | | `SET XACT_ABORT` | honoured | not honoured | | `printf`-style substitution | no (use `FORMATMESSAGE`) | yes | The documentation's advice is direct: new applications should use `THROW` instead of `RAISERROR`. `RAISERROR ... WITH NOWAIT` at severity 10 or lower remains useful for progress messages, because it sends text to the client immediately without entering `CATCH`. ## What CATCH never sees - **Compile errors** such as syntax errors in the same batch, and **name resolution errors** at the same level, for example a table that did not exist when deferred name resolution let the procedure compile. They go to the caller. The same errors raised inside a called procedure or `sp_executesql` are caught, because they occur at a lower level. - Errors with severity 20 or higher that end the session's task processing. - **Attentions**: a client query timeout or cancel. The batch simply stops, and SQL Server does **not** roll back the open transaction. With `XACT_ABORT OFF` the transaction is orphaned and keeps its locks until something rolls it back or the connection closes; with `XACT_ABORT ON` it is rolled back. - A session ended with `KILL`. The attention case is the strongest argument for `XACT_ABORT ON` even when every procedure has a `CATCH` block.
- Why does a client query timeout leave a transaction open, and what prevents it?A timeout makes the client send an attention, which stops the batch without running any `CATCH` block, and SQL Server does not roll back the open transaction on an attention. The orphaned transaction keeps its locks until it is rolled back or the connection closes. `SET XACT_ABORT ON` makes the engine roll it back; otherwise the application must roll back itself.
- Which errors does TRY...CATCH miss even inside the TRY block?Compile errors such as syntax errors in the same batch, and object name resolution errors at the same level, return to the caller instead. Severity 10 or lower is informational and never enters `CATCH`, and severity 20 or above that stops the session's task, attentions and `KILL` bypass it too. Errors inside a called procedure or `sp_executesql` are caught, because they occur at a lower level.
- Any error inside a transaction rolls the whole transaction back automatically.
- TRY...CATCH catches syntax errors in the same batch.
- If XACT_STATE() is -1 you can still commit the work done so far.
- RAISERROR(ERROR_MESSAGE(), 16, 1) re-raises the error with its original number.
- @@TRANCOUNT shows whether the transaction can still be committed.
- A CATCH block runs when the client's query times out.