SQL Server › Error Handling with TRY CATCH

How does a TRY CATCH block work in SQL Server, and why is it useful?

Beginner

Answer

A TRY CATCH block lets you run a piece of SQL code inside the TRY section, and if any error occurs during its execution, control immediately jumps to the CATCH section instead of stopping the entire batch abruptly, letting you handle the error gracefully, such as logging it or rolling back a transaction.
BEGIN TRY
  INSERT INTO Orders (OrderId, Amount) VALUES (1, 100);
END TRY
BEGIN CATCH
  PRINT 'An error occurred: ' + ERROR_MESSAGE();
END CATCH;
Real-world example An order processing script catches an error that occurs when trying to insert a duplicate order id, printing a clear message instead of letting the entire batch fail with an unhandled, confusing error.

Common follow-ups: What types of errors are not caught by a TRY CATCH block?;How do you retrieve details about the specific error that occurred inside the CATCH block?