Exception Handling In SQL Server

If you are aware of any programming language, then you must know about exception handling like “Try, Catch” blocks. This is used in SQL Servers as well.
 
Firstly, SQL Server 2005 introduced Try-Catch blocks to handle errors effectively from the backend side.
 
The handling of exceptions can provide more and specific information about errors and translate those errors into some meaningful message to make the user understand by logging and saving to the table.
 
Now, we will understand in depth how it works.
 
Syntax
  1. BEGIN TRY  
  2. //Your Logic  
  3. END TRY  
  4. BEGIN CATCH  
  5. //if an exception came in try block you can handle here  
  6. END  CATCH  
Your logic should come inside the BEGIN TRY and END TRY . If during any transaction in any line inside the try block an exception is raised, then it will send to CATCH block .
Inside the Catch block you will have that exception. You can do anything with that exception like you can log the error or report that error or you can throw that exception to the front end user with any meaningful statement. In this way we can try to fix raised exceptions.
 
We can use some special in-built functions inside the catch block, Let's have a look.
  • ERROR_NUMBER() - returns the internal number of the error.
  • ERROR_STATE() - returns the information about the source.
  • ERROR_SEVERITY() - returns the severity of error that occurred. We can call anywhere but it returns severity if it is in the catch block else it returns NULL.
  • ERROR_PROCEDURE() - returns the Name of the Procedure.
  • ERROR_LINE() - returns the line number where the error occurred.
  • ERROR_MESSAGE() - returns the exact error message.
This information is very useful when you are doing big projects like banking, ticket booking apps, etc. When we are working on such projects, there comes the COMMIT and ROLLBACK keywords into the picture.
 
For eg: We have to write COMMIT in the try block and ROLLBACK into the Catch block. Suppose a transaction is going on and in the middle some error occurs --  then it will go to Catch block and ROLLBACK the whole Transaction and save the error related log. If the transaction is complete we can COMMIT.
 
Exception Handling In SQL Server
 
As in the above Image, we are doing divideByZero which will return an error and the Catch block is executed.
 
From the Catch block, we get the error-related information. As we see ErrorProcedure is getting NULL because we are not writing all this into a Stored Procedure.
 
We got two tables as a result because we have written two select statements, one in the Try block and another in the Catch block.

Now we will have one more example with Stored Procedure and make a log of the Error,
 
Create a Table like below,
  1. CREATE TABLE DB_Errors_Logs  
  2. (  
  3.    ID                       INT IDENTITY(1, 1),  
  4.    UserName                 VARCHAR(MAX),  
  5.    ErrorNumber              INT,  
  6.    ErrorState               INT,  
  7.    ErrorSeverity            INT,  
  8.    ErrorLine                INT,  
  9.    ErrorProcedure           VARCHAR(MAX),  
  10.    ErrorMessage             VARCHAR(MAX),  
  11.    EmployeeName             VARCHAR(100),  
  12.    CreatedBy                INT,  
  13.    ErrorCreatedDateTime     DATETIME  
  14. )  
Here is the Stored Procedure for inserting the employee,
  1. ALTER PROCEDURE [dbo].[InsertEmployees]  
  2. (  
  3.    @EmployeeName VARCHAR(100),  
  4.    @Gender char(1),  
  5.    @Emailid nvarchar(100)=null,  
  6.    @Age int =null,  
  7.    @Phoneno NVARCHAR(10)=null,  
  8.    @Departmentid int,  
  9.    @CreatedBy int  
  10. )  
  11. AS  
  12. BEGIN  
  13. BEGIN TRY  
  14. begin tran  
  15. insert into employee(EmpName,Gender,Emailid,Age,Phoneno,Departmentid )   
  16. values(@EmployeeName,@Gender,@Emailid,@Age,@Phoneno,@Departmentid)  
  17. commit  
  18. END TRY  
  19. BEGIN CATCH  
  20. rollback  
  21. INSERT INTO dbo.DB_Errors_Logs(UserName,ErrorNumber,ErrorState,ErrorSeverity,ErrorLine,ErrorProcedure,ErrorMessage,EmployeeName,CreatedBy,ErrorCreatedDateTime)  
  22. VALUES (   
  23.    SUSER_SNAME(),  
  24.    ERROR_NUMBER(),  
  25.    ERROR_STATE(),  
  26.    ERROR_SEVERITY(),  
  27.    ERROR_LINE(),  
  28.    ERROR_PROCEDURE(),  
  29.    ERROR_MESSAGE(),  
  30.    @EmployeeName,  
  31.    @CreatedBy,  
  32.    GETDATE()  
  33. )  
  34. END CATCH  
  35. END  
  36. GO  
Exception Handling In SQL Server
In the above image, we have inserted the record successfully, So it is displaying as 1 row affected.
 
Exception Handling In SQL Server 
There we got two results,
  1. 0 rows affected - Nothing is inserted in the Employee table.
  2. 1 row affected - error information is inserted in the DB_Errors_Logs table.
In the next article, we will learn advanced exception handling in SQL.