SIGN UP MEMBER LOGIN:    
ARTICLE

Exception Handling in SQL Server

Posted by Senthilkumar Articles | SQL December 15, 2011
In this article, we will learn how to handle the exception in SQL server and store the error log in a SQL server table for reference.
Reader Level:

Introduction

Handling errors in SQL Server became easy with a number of different ways. SQL Server 2005 introduced the new option that helps to handle the errors effectively. Sometimes we cannot capture the errors which occurred in the end user. Even if we want to know the errors which occurred in the end user, we need to write the code to send it to us. It creates an additional overhead for the server.

SQL Server 2005 introduced the TRY...CATCH statement which helps us to handle the errors effectively in the back end. This handling of the exception can provide additional information about the errors.

TRY...CATCH

The TRY...CATCH statement works the same as in the programming languages. First it gets executed in the SQL statement which we have written in the TRY block and if any error occurs, then it will get executed the CATCHblock.

There are a number of error handling property statements like the following:

 ERROR_NUMBER()   ERROR_STATE() ERROR_SEVERITY() ERROR_LINE() ERROR_PROCEDURE()   ERROR_MESSAGE()
Normally, SQL Server stores the default error messages which occurred in the execution in the following system table:
  SELECT * FROM SYS.MESSAGES

But we can create our own error message details with the help of this exception handling.

Handling the Exception using TRY...CATCH

The below example shows the practical implementation of TRY...CATCH exception handling technique in Northwinddatabase.

USE [NorthWind]
GO

IF OBJECT_ID('dbo.ErrorTracer') IS NOT NULL
BEGIN
      DROP TABLE dbo.ErrorTracer
      PRINT 'Table dbo.ErrorTracer Dropped'
END
GO
 
CREATE TABLE ErrorTracer
(
  iErrorID INT PRIMARY KEY IDENTITY(1,1),
  vErrorNumber INT,
  vErrorState INT,
  vErrorSeverity INT,
  vErrorLine INT,
  vErrorProc VARCHAR(MAX),
  vErrorMsg VARCHAR(MAX),
  vUserName VARCHAR(MAX),
  vHostName VARCHAR(MAX),
  dErrorDate DATETIME DEFAULT GETDATE()
)
 
IF OBJECT_ID('dbo.ErrorTracer') IS NOT NULL
BEGIN
      PRINT 'Table dbo.ErrorTracer Created'
END
GO
 
IF OBJECT_ID('Proc_InsertErrorDetails') IS NOT NULL

BEGIN
      DROP PROCEDURE [dbo].[Proc_InsertErrorDetails]
    PRINT 'Procedure Proc_InsertErrorDetails Dropped'
END
GO
 
CREATE PROCEDURE Proc_InsertErrorDetails
AS
/*
Purpose    : Insert the error details occurred in the SQL query
Input      : Insert the details which receives from the TRY...CATCH block
Output     : Insert the details of received errors into the ErrorTracer table
Created By : Senthilkumar
Created On : July 17, 2009
*/
BEGIN
   SET NOCOUNT ON
   SET XACT_ABORT ON
 
   DECLARE @ErrorNumber VARCHAR(MAX) 
   DECLARE @ErrorState VARCHAR(MAX) 
   DECLARE @ErrorSeverity VARCHAR(MAX) 
   DECLARE @ErrorLine VARCHAR(MAX) 
   DECLARE @ErrorProc VARCHAR(MAX) 
   DECLARE @ErrorMesg VARCHAR(MAX) 
   DECLARE @vUserName VARCHAR(MAX) 
   DECLARE @vHostName VARCHAR(MAX)
 
  SELECT  @ErrorNumber = ERROR_NUMBER() 
       ,@ErrorState = ERROR_STATE() 
       ,@ErrorSeverity = ERROR_SEVERITY() 
       ,@ErrorLine = ERROR_LINE() 
       ,@ErrorProc = ERROR_PROCEDURE() 
       ,@ErrorMesg = ERROR_MESSAGE() 
       ,@vUserName = SUSER_SNAME() 
       ,@vHostName = Host_NAME() 
 
INSERT INTO ErrorTracer(vErrorNumber,vErrorState,vErrorSeverity,vErrorLine,_
      vErrorProc,vErrorMsg,vUserName,vHostName,dErrorDate) 
VALUES(@ErrorNumber,@ErrorState,@ErrorSeverity,@ErrorLine,@ErrorProc,_
      @ErrorMesg,@vUserName,@vHostName,GETDATE()) 
END
 
IF OBJECT_ID('Proc_InsertErrorDetails') IS NOT NULL
BEGIN
    PRINT 'Procedure Proc_InsertErrorDetails Created'
END
GO
 
IF OBJECT_ID('Proc_ExceptionHandlingExample') IS NOT NULL
BEGIN
      DROP PROCEDURE [dbo].[Proc_ExceptionHandlingExample]
    PRINT 'Procedure Proc_ExceptionHandlingExample Dropped'
END
GO
 
CREATE PROCEDURE Proc_ExceptionHandlingExample
AS
BEGIN
/*
Purpose    : Sample procedure for check the Try...Catch
Output     : It will insert into ErrorTracer table if this
                  stored procedure throws any error
Created By : Senthilkumar
Created On : July 17, 2009
*/
   SET NOCOUNT ON
   SET XACT_ABORT ON
  
   BEGIN TRY
      SELECT 15/0
   END TRY
   BEGIN CATCH
      EXEC Proc_InsertErrorDetails
   END CATCH
END
 
IF OBJECT_ID('Proc_ExceptionHandlingExample') IS NOT NULL
BEGIN
    PRINT 'Procedure Proc_ExceptionHandlingExample Created'
END
GO
EXEC Proc_ExceptionHandlingExample
SELECT * FROM ErrorTracer

Steps:

Step 1: Create the custom error table with the name "ErrorTracer".

Step 2: Write the common Stored procedures for handling the current exception in the name of Proc_InsertErrorDetails which will help us to insert the error details into step1 created table.

Step 3: Write a sample procedure and execute with the exception handling using TRY...CATCH statement. Whenever an error occurs, it will call the Proc_InsertErrorDetails and that will insert the error details. 

Step 4: Now, check the ErrorTracer table that will list out the captured error details.

Conclusion

This customized error handling techniques help us to improve the back end error details effectively. We have given the date and username details in the table that will help you to find the error details based on the date and username respectively.

Login to add your contents and source code to this article
share this article :
post comment
 

Hey dude nice one........

Posted by Satish A Dec 21, 2011

Hi Senthilkumar. Nice article.

Posted by Monika Arora Dec 18, 2011

Hey this is my old article... when i was writing article in code project in 2009 it was published and went on well... This is very practical usage of article and published to the c-sharpcorners well :-). Thanks guys for reading this.

Posted by Senthilkumar Dec 17, 2011

Good article.

Posted by James Dec 17, 2011

Dear Senthilkumar it's a great effort keep it up.

Posted by Michell Johnson Dec 16, 2011
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor