Handling Errors with TRY...CATCH and THROW
This lesson explains TRY...CATCH blocks, the error functions and raising or re-raising errors with THROW.
Learning outcomes
After completing this lesson, you will be able to:
- Describe which errors TRY...CATCH catches.
- Explain the difference between THROW and RAISERROR.
- Identify how to log an error and pass it to the caller.
TRY...CATCH blocks
Statements in BEGIN TRY ... END TRY run normally; when one raises an error with severity above 10 that does not close the connection, control passes to the BEGIN CATCH ... END CATCH block that immediately follows. Inside CATCH, error functions describe the error, as the following table lists. They return NULL outside a CATCH block.
| Function | Returns |
|---|---|
| ERROR_NUMBER() | The error number, such as 2627 for a duplicate key or 1205 for a deadlock |
| ERROR_MESSAGE() | The complete message text |
| ERROR_SEVERITY() and ERROR_STATE() | Severity and state |
| ERROR_PROCEDURE() and ERROR_LINE() | Where the error occurred |
Some errors are not caught by the TRY block in which they occur: compile errors such as syntax errors and deferred name resolution errors in the same batch, and errors with severity 20 or higher that end the connection. Errors in a called procedure or in dynamic SQL are caught by the caller's TRY block.
Caught or not?
THROW and RAISERROR
THROW without arguments, inside CATCH, re-raises the original error with its original number, which is the usual way to log an error and pass it on. THROW 50001, N'Message', 1 raises a custom error; custom numbers must be 50000 or higher, and the severity is always 16. The statement before THROW must end with a semicolon. THROW always ends the batch, while the older RAISERROR supports formatting and lower severities but does not stop execution, so new code uses THROW, with FORMATMESSAGE when message formatting is needed.
BEGIN TRY
IF NOT EXISTS (SELECT 1 FROM Sales.Customer WHERE CustomerID = @CustomerID)
THROW 50010, N'Customer does not exist.', 1;
INSERT INTO Sales.Orders (CustomerID, OrderDate, Status) VALUES (@CustomerID, SYSUTCDATETIME(), 'Open');
END TRY
BEGIN CATCH
INSERT INTO dbo.ErrorLog (Number, Message, ProcName, Line, LoggedUtc)
VALUES (ERROR_NUMBER(), ERROR_MESSAGE(), ERROR_PROCEDURE(), ERROR_LINE(), SYSUTCDATETIME());
THROW; -- re-raise to the caller
END CATCH;THROW and RAISERROR
Designing error handling
Errors should either be handled meaningfully or passed on; swallowing them in an empty CATCH hides failures from the application. A typical procedure logs the error, rolls back any open transaction and re-throws. Validation that the caller should see uses THROW with a clear custom number and message so the application can respond, and messages never include sensitive data such as connection details.
Good error handling
Preserving the original error
A procedure's CATCH block runs RAISERROR('Insert failed', 16, 1). Support staff complain that every failure looks the same, and the application cannot tell duplicate keys from other errors. What should the developer change?
Log the details with the error functions and end the CATCH block with THROW;, which re-raises the original error, such as 2627 for a duplicate key, with its original message. The custom RAISERROR replaces the number with 50000 and the message with generic text. Returning ERROR_NUMBER() in a result set without raising an error would make failures look like success to callers that only check for exceptions.
What severity does a custom THROW raise?
Show answer
Always 16; custom error numbers must be 50000 or higher.
Exam Tips
Remember for the exam
- Re-raise the original error: THROW with no arguments inside CATCH.
- Custom errors: THROW with a number of 50000 or higher; severity is 16.
- Compile errors in the same batch are not caught by TRY.
- End the statement before THROW with a semicolon.