Error handling in Transact-SQL (T-SQL) is crucial for managing unexpected issues that may arise during the execution of SQL statements.
TRY-CATCH Block
This is the primary mechanism for handling errors in T-SQL. It functions similarly to exception handling in languages like C#. It allows us to enclose a block of T-SQL statements within a TRY block and then specify one or more CATCH blocks to handle different types of errors that may occur within the TRY block.
BEGIN TRY
-- T-SQL statements that may cause errors
END TRY
BEGIN CATCH
-- Error handling code
END CATCH
RAISE ERROR
This function can be used to raise a custom error message or exception within the T-SQL code. It allows you to specify an error number, error message, and severity level.
RAISEERROR('Error Message', 20, 1);
Error Functions
T-SQL provides several functions to retrieve information about errors that occur. Some commonly used functions are given below.
- ERROR_NUMBER(): Returns the number of the error.
- ERROR_MESSAGE(): Provides the actual error message text associated with the error.
- ERROR_SEVERITY(): Returns the severity level of the error (same as the second parameter in RAISERROR).
- ERROR_STATE(): Returns the state number of the error.
- ERROR_PROCEDURE(): Returns the name of the stored procedure or trigger where the error originated.
THROW Statement
It is used to raise an exception and terminate the batch, function, or procedure. It simplifies error handling by eliminating the need for RAISEERROR and providing clearer control over error messages.
BEGIN TRY
-- T-SQL statements
THROW 50001, 'Custom error message', 1;
END TRY
BEGIN CATCH
-- Error handling code
END CATCH
Nested TRY-CATCH Blocks
We can place a try block inside another try block. This allows us to handle exceptions at different levels of our code.
BEGIN TRY
BEGIN TRY
-- Nested T-SQL statements
END TRY
BEGIN CATCH
-- Nested error handling code
END CATCH
END TRY
BEGIN CATCH
-- Outer error handling code
END CATCH
Example
BEGIN TRY -- Outer TRY block
PRINT 'Outer TRY block executing...'
BEGIN TRY -- Inner TRY block
-- Code that might generate an error (e.g., division by zero)
SELECT 1 / 0;
PRINT 'Inner TRY block completed!'
END TRY
BEGIN CATCH -- Inner CATCH block (for errors within inner TRY)
PRINT 'Error in inner TRY block!';
-- Handle the specific error here (e.g., log the error)
END CATCH
PRINT 'Continuing outer TRY block...'
END TRY
BEGIN CATCH -- Outer CATCH block (for any errors not caught inside)
PRINT 'Error in outer TRY block or inner TRY block not handled!';
-- Handle unhandled errors here (e.g., notify administrator)
END CATCH

Join the conversation! Your thoughts help the community grow.