Introduction
This article will teach us how to implement exception handling in SQL Server. SQL Server provides TRY and CATCH blocks for exception handling.
Exception Handling in SQL Server
An error condition during program execution is called an exception, and the mechanism for resolving such an exception is known as exception handling. We can put all T-SQL statements into a TRY BLOCK, and the code for exception handling can be put into a CATCH block. We can also generate user-defined errors using a THROW block.
![Exception Handling in SQL Server]()
Syntax of Exception Handling
![Syntax of Exception Handling]()
BEGIN TRY
/* T-SQL Statements */
END TRY
BEGIN CATCH
- Print Error OR
- Rollback Transaction
END CATCH
In exception handling, all T-SQL statements are put into a try block. If all statements execute without any error, then everything is OK else. Control will go to the catch block.
Types of SQL Server Exceptions
SQL Server contains the following two types of exceptions:
- System Defined
- User Defined
System Defined Exception
In a System Defined Exception, the system generates exceptions (errors).
Example
Output
- Error Occur that is:
- Divide by zero error encountered
User Defined Exception
This type of exception is user-generated, not system generated.
Output
- Error Occur
- Error Occur that is:
- Number Is Even
Here 60000 denotes the error number, and 5 denotes the state to associate with the message.
The following are system functions and the keyword used within a catch block:
Now we will see some examples to help understand all these functions and keywords.
First, create a table and enter some value into the table as in the following:
Insert data into Employee.
Now execute a select command.
![execute select command]()
Example 1. (@@ERROR)
@@ERROR returns the error number for the last executed T-SQL statements. It returns 0 if the previous Transact-SQL statement encountered no errors; else returns an error number.
Output
- Msg 547, Level 16, State 0, Line 1
- The UPDATE statement conflicted with the CHECK constraint "CK__Employee__Salary__68487DD7". The conflict occurred in database "Home_Management," table "dbo. Employee", column 'Salary.'
The statement has been terminated.
A check constraint violation occurred.
Example 2. (ERROR_NUMBER)
ERROR_NUMBER() returns the error number that caused the error. It returns zero if called outside the catch block.
Output
![catch block]()
Now a question develops of what is diff @@ERROR and ERROR_NUMBER. Let me explain.
- ERROR_NUMBER can only be used in a catch block; outside a catch block, it returns Null, but @@ERROR can be used inside or outside the catch block (see Example 1).
- ERROR_NUMBER is a contrast to @@ERROR, that only returns the error number in the statement immediately after the one that causes an error or the first statement of a CATCH block.
Now we will see an example and observe the differences between them.
Output
![take to example]()
Output
![error that caused]()
Example 3. (ERROR_MESSAGE)
ERROR_MESSAGE returns the message text of the error that caused the error. The return type of ERROR_MESSAGE is nvarchar(4000).
Output
- The UPDATE statement conflicted with the CHECK constraint "CK__Employee__Salary__68487DD7". The conflict occurred in database "Home_Management," table "dbo.Employee", column 'Salary.'
Example 4. ( ERROR_STATE)
ERROR_STATE returns the state number of the error. The return type of ERROR_STATE is INT.
Output
![INT]()
Example 5. (ERROR_LINE)
ERROR_LINE returns the line number at which an error occurred. The return type of ERROR_LINE is INT.
Output
![ERROR LINE]()
Example 6. (ERROR_PROCEDURE)
ERROR_PROCEDURE returns the name of the Stored Procedure or trigger where an error occurred. The return type of ERROR_PROCEDURE is nvarchar(128).
Return value
Return value returns the Stored Procedure Name if an error occurs in a Stored Procedure or trigger and the catch block is called.
It returns NULL if the error did not occur within a Stored Procedure or trigger or if it is called outside the scope of a CATCH block.
First, we create a Stored Procedure.
Now execute this Stored Procedure.
Output
![execute this Stored Procedure]()
Example 7. (ERROR_SEVERITY)
ERROR_SEVERITY returns the severity of the error. The return type of ERROR_SEVERITY is INT.
Output
![ErrorSeverity]()
The severity level of an error message indicates the type of problem that Microsoft® SQL Server encountered. In the preceding example, the Severity Level is 16. That means that the user can remove the error.
Some important severity levels are:
13 |
Indicates transaction deadlock errors. |
14 |
Indicates security-related errors, such as permission denied. |
15 |
Indicates syntax errors in the Transact-SQL command. |
16 |
Indicates general errors that the user can correct. |
Example 8. (RAISERROR)
RAISEERROR generates an error message and initiates error processing for the session.
Output
![An Error Is Occur]()
In RAISERROR(N'An Error Is Occur',16,3), the first argument represents the error message, the second represents the Severity Level, and the last represents the Error State.
Example 9. (GOTO)
GOTO causes a jump to a specific step or statement. It alters the flow of execution to a label. We declare some labels in batches and alter we can move to a specific label. GOTO can exist within a conditional control-of-flow statement, statement blocks, or procedures but cannot go to a label outside the batch. GOTO cannot be used to jump into a TRY or CATCH scope.
Output
- Goto exercise
- Var Is Even
Example 10
Output
![ErrorNumber]()
Exercise 11. (Transaction Management)
Exception handling is mainly used for Transaction Management. Let us see an example.
Output
![Output]()
When to use Exception Handling?
- In Transaction Management to Rollback the transaction.
- While using cursors in SQL Server.
- When implementing a DML Query (insert, update, or delete) for checking and handling the error.
Conclusion
This article taught us about Exception Handling in SQL Server with different types of exceptions and handling these exceptions by using TRY-Catch blocks.