SQL Server › Error Handling with TRY CATCH

How do nested TRY CATCH blocks work, and when would you use them in a complex stored procedure?

Advanced

Answer

A CATCH block can contain its own nested TRY CATCH block, letting you attempt a recovery action, like retrying an operation or performing partial cleanup, while still safely catching any new error that might occur during that recovery attempt itself, preventing an error inside your error handling code from crashing the entire procedure unexpectedly.
BEGIN TRY
  -- main operation
END TRY
BEGIN CATCH
  BEGIN TRY
    -- attempt cleanup or logging
    EXEC LogError;
  END TRY
  BEGIN CATCH
    PRINT 'Logging itself failed: ' + ERROR_MESSAGE();
  END CATCH
END CATCH;
Real-world example A critical financial procedure wraps its error logging call in its own nested TRY CATCH block, ensuring that even if the logging system itself has a problem, the original error handling process does not crash unexpectedly.

Common follow-ups: How deep can TRY CATCH blocks realistically be nested in SQL Server?;What are some real world scenarios where nested error handling like this becomes necessary?