Session 15 XP Error Handling
Session 15 XP Error Handling
Server
2012
Session: 15
Error handling in SQL Server has become easy through a number of different
techniques such as:
• SQL Server provides the TRY…CATCH statement that helps to handle errors
effectively at the back end.
• SQL Server also provides a number of system functions that print error
related information, which can help fix errors easily.
A Transact-SQL programmer must identify the type of the error and then determine
how to handle or overcome it.
Syntax Errors
Are detected by SQL
Server before beginning
the execution process of a
Are the errors that Transact-SQL block or
occur when code cannot stored procedure.
be parsed by SQL Server.
Run-time Errors
Most important things that users need to take care of is error handling.
Users also have to take care of handling exception and errors while designing the
database.
When executing some DML statements such as INSERT, DELETE, and UPDATE,
users can handle errors to ensure correct output.
When a transaction fails and the user needs to rollback the transaction, an
appropriate error message can be displayed.
When working with cursors in SQL Server, users can handle errors to ensure
correct results.
Passes control to the CATCH block that may contain one or more statements, if an
error occurs in the TRY block.
Syntax:
BEGIN TRY
{ sql_statement | statement_block }
END TRY
BEGIN CATCH
[ { sql_statement | statement_block } ]
END CATCH
[ ; ]
where,
sql_statement: specifies any Transact-SQL statement.
statement_block: specifies the group of Transact-SQL statements in a
BEGIN…END block.
A TRY…CATCH construct will catch all run-time errors that have severity higher than
10 and that do not close the database connection.
Both TRY and CATCH blocks can contain nested TRY…CATCH constructs
If the CATCH block encloses a nested TRY…CATCH construct, any error in the
nested TRY block passes the control to the nested CATCH block
If there is no nested TRY…CATCH construct the error is passed back to the caller
TRY…CATCH constructs can also catch unhandled errors from triggers or stored
procedures that execute through the code in TRY block
© Aptech Ltd. Error Handling / Session 15 9
SQL
Server
2012
Good practice is to display error information along with the error, so that it can help
to solve the error quickly and efficiently.
System functions need to be used in the CATCH block to find information about the
error that initiated the CATCH block to execute.
Functions return NULL when they are called outside the scope of the CATCH block.
Output:
Uncommittable Transactions
@@ERROR function returns the error number for the last Transact-SQL statement
executed.
Syntax:
@@ERROR
Following code snippet shows how to use @@ERROR to check for a constraint
violation:
USE AdventureWorks2012;
GO
BEGIN TRY
UPDATE HumanResources.EmployeePayHistory
SET PayFrequency = 4
WHERE BusinessEntityID = 1;
END TRY
BEGIN CATCH
IF @@ERROR = 547
PRINT N'Check constraint violation has occurred.';
END CATCH
Output:
Check constraint violation has occurred.
Starts the error processing for a session and displays an error message.
Returns the message as a server error message to the calling application or to the
associated CATCH block of a TRY…CATCH construct.
Syntax:
RAISERROR ( { msg_id | msg_str | @local_variable }
{ ,severity ,state }
[ ,argument [ ,...n ] ] )
[ WITH option [ ,...n ] ]
where,
msg_id: specifies the user-defined error message number that is stored in the
sys.messages catalog view using the sp_addmessage.
msg_str: Specifies the user-defined messages with formatting. msg_str is a
string of characters with optional embedded conversion specifications. A
conversion specification has the following format:
% [[flag] [width] [. precision] [{h | l}]] type
Output:
This is error message serial number 23.
Following code snippet shows how to use RAISERROR statement to return the
same string:
RAISERROR (N'%*.*s', 10, 1, 7, 3, N'Hello world');
GO
RAISERROR (N'%7.3s', 10, 1, N'Hello world');
GO
ERROR_STATE system function returns the state number of the error that causes
the CATCH block of a TRY…CATCH construct to execute.
Syntax:
ERROR_STATE ( )
ERROR_SEVERITY function returns the severity of the error that causes the
CATCH block of a TRY…CATCH construct to be executed.
Syntax:
ERROR_SEVERITY ( )
Following code snippet shows how to display the severity of the error:
BEGIN TRY
SELECT 217/0;
BEGIN CATCH
SELECT ERROR_SEVERITY() AS ErrorSeverity;
END CATCH;
GO
END TRY
Syntax:
ERROR_PROCEDURE ( )
ERROR_NUMBER system function when called in a CATCH block returns the error
number of the error that causes the CATCH block of a TRY…CATCH construct to be
executed.
Syntax:
ERROR_NUMBER ( )
BEGIN TRY
SELECT 217/0;
END TRY
BEGIN CATCH
SELECT ERROR_NUMBER() AS ErrorNumber;
END CATCH;
GO
ERROR_MESSAGE function returns the text message of the error that causes the
CATCH block of a TRY…CATCH construct to execute.
Syntax:
ERROR_MESSAGE ( )
• ERROR_MESSAGE function is called in the CATCH block, it returns the full text of
the error message that causes the CATCH block to execute.
• ERROR_MESSAGE returns NULL if it is called outside the scope of a CATCH block.
Following code snippet shows how to use ERROR_MESSAGE in a CATCH block:
BEGIN TRY
SELECT 217/0;
END TRY
BEGIN CATCH
SELECT ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO
ERROR_LINE function returns the line number at which the error occurred in the
TRY…CATCH block.
Syntax:
ERROR_LINE ( )
• ERROR_LINE function is called in the CATCH block, it returns the line number
where the error has occurred.
• ERROR_LINE returns the line number in that trigger or stored procedure where
the error has occurred.
Following code snippet shows how to use ERROR_LINE in a CATCH block:
BEGIN TRY
SELECT 217/0;
END TRY
BEGIN CATCH
SELECT ERROR_LINE() AS ErrorLine;
END CATCH;
GO
Following types of errors are not handled by a CATCH block that occur at the same
execution level as that of the TRY…CATCH construct:
• Compile errors such as syntax errors that restrict a batch from running.
• Errors that arise in the statement-level recompilation such as object name
resolution errors occurring after compiling due to deferred name resolution.
Following code snippet shows how an object name resolution error is generated
by the SELECT statement:
USE AdventureWorks2012;
GO
BEGIN TRY
SELECT * FROM Nonexistent;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_MESSAGE() AS ErrorMessage;
END CATCH
Following code snippet shows how the error message is displayed in such a case:
Syntax:
THROW [ { error_number | @local_variable },
{ message | @local_variable },
{ state | @local_variable }
] [ ; ]
where,
error_number: specifies a constant or variable that represents the
error_number as int.
message: specifies a variable or string that defines the exception message as
nvarchar(2048).
state: specifies a variable or a constant between 0 and 255 that specifies the
state to associate with state of message as tinyint.
Following code snippet shows the use of THROW statement to raise an exception again:
USE tempdb;
GO
CREATE TABLE dbo.TestRethrow
( ID INT PRIMARY KEY
);
BEGIN TRY
INSERT dbo.TestRethrow(ID) VALUES(1);
INSERT dbo.TestRethrow(ID) VALUES(1);
END TRY
BEGIN CATCH
PRINT 'In catch block.';
THROW;
END CATCH;
Output:
(1 row(s) affected)
(0 row(s) affected)
In catch block.
Msg 2627, Level 14, State 1, Line 6
Violation of PRIMARY KEY constraint 'PK__TestReth__3214EC27AAB15FEE'.
Cannot insert duplicate key in object 'dbo.TestRethrow'. The duplicate
key value is (1).
● Syntax errors are the errors that occur when code cannot be parsed by SQL Server.
● Run-time errors occur when the application tries to perform an action that is
neither supported by Microsoft SQL Server nor by the operating system.
● TRY…CATCH statements are used to handle exceptions in Transact-SQL.
● TRY…CATCH constructs can also catch unhandled errors from triggers or stored
procedures that execute through the code in a TRY block.
● GOTO statements can be used to jump to a label inside the same TRY…CATCH block
or to leave a TRY…CATCH block.
● Various system functions are available in Transact-SQL to print error information
about the error that occurred.
● The RAISERROR statement is used to start the error processing for a session and
displays an error message.