SQL Server Interview Question #117
What is TRY...CATCH in SQL Server?
Views, Stored Procedures & User-Defined Functions Mid-Level Intermediate
Detailed Explanation
TRY...CATCH provides structured error handling in T-SQL. Statements that might fail are placed in a TRY block, while error-handling logic is placed in CATCH.
Inside CATCH, functions such as ERROR_NUMBER, ERROR_MESSAGE, ERROR_LINE, ERROR_PROCEDURE, and ERROR_SEVERITY provide error details. THROW is commonly used to propagate an error after cleanup or transaction handling.
Code Example
BEGIN TRY
UPDATE dbo.Products
SET Price = Price * 1.10
WHERE CategoryId = 10;
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber,
ERROR_MESSAGE() AS ErrorMessage;
THROW;
END CATCH;