Skill 1.3.8
Implement error handling
Key Concepts
A BEGIN TRY ... END TRY BEGIN CATCH ... END CATCH block moves control to CATCH when an error of severity above 10 occurs. Inside CATCH, ERROR_NUMBER(), ERROR_MESSAGE(), ERROR_SEVERITY(), ERROR_STATE(), ERROR_LINE() and ERROR_PROCEDURE() describe the error. THROW without arguments re-raises the original error, and THROW 50001, 'message', 1 raises a custom error; THROW always ends the batch, unlike RAISERROR, which is the older form.
SET XACT_ABORT ON makes most runtime errors roll back the whole transaction, which is the recommended setting in procedures that open transactions. In CATCH, XACT_STATE() returns 1 (committable), -1 (uncommittable, must roll back) or 0 (no transaction), so the handler rolls back when it is not 0 and then re-raises. Transient errors, such as deadlock victim 1205, can be retried in a loop with a limited number of attempts. Compile errors and some severe errors are not caught by the same TRY block.