Click here to Skip to main content
Licence 
First Posted 18 Jan 2005
Views 47,865
Bookmarked 27 times

Simplest way of Exception Handling specially for database applications

By | 18 Jan 2005 | Article
Simplest way of exception handling, specially for database applications.
 
Part of The SQL Zone sponsored by
See Also

Introduction

This article and the source provided demonstrate how you can handle exceptions in .NET applications in a generic way. This will ensure that there are no unhandled exceptions in your application thread.

Background

Exception handling is an important part of all applications. A few days ago, I was writing a database oriented application that consisted of over 100 forms. During the design of my application, I got different ways of exception handling, but actually I was in search of a way that was the shortest and one that requires minimum lines of code. For this project, I wrote about 10 to 12 lines of code.

Using the code

For handling exceptions on application thread level, I handle the application's exception event as follows:

static void Main() 
{ 
  Application.ThreadException+= new 
     System.Threading.ThreadExceptionEventHandler(Application_ThreadException); 
  Application.Run(new testExceptionHandler()); 
}

Now, whenever there is any exception that occurs in an application thread, this event will be called.

As I have already stated, it was a database application, now there was a challenge of how I will identify specific exceptions like primary key violation etc..

For this, in the MDI form in that application, I declared a string variable that will later contain the active form name.

Fortunately I was using SqlClient that has a SqlException class, this will be thrown if there is any database related issue. I handle this as follows:

private static void Application_ThreadException(object sender, 
                         System.Threading.ThreadExceptionEventArgs e)
{
   try
   {
        if(e.Exception is SqlException)
        {
             SqlException ex = (SqlException)e.Exception; 
             if (ex.Number == 547)
                ErrorMessage("Record cannot be deleted or changed " + 
                               "as it is being used somewhere else");
    
             else if (ex.Number == 2627)
                ErrorMessage("Record cannot be saved, as another " + 
                             "record with this key already exists");
        
             else
                ErrorMessage(ex.Message.ToString());
        }
        else
             ErrorMessage("System Error :"+e.Exception.Message.ToString());

    }
    catch(Exception ex)
    {
        ErrorMessage("System Error: Reporting to log");
    }
}

sqlexception object contains a number attribute that identifies the type of sqlexception thrown.

I have tested this method in my application, it is running well. For a more descriptive message I have used the form name of the active form for intimating the user about the problem.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

farukh ali farooq



Pakistan Pakistan

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Generalodbcexception... Pinmemberfuhaizah17:48 23 Mar '06  
GeneralSometimes a generic approach isn't suitable. PinmemberCharlie Williams6:10 18 Jan '05  
While I understand the desire to reduce what is seen as repetitive code, exception handling should be about more than making sure the application doesn't crash. I think this is especially true for data-centric applications.
 
Exception handling should be done as close as possible to the source of the exception so that the code can actually respond in a way that's appropriate to the situation, instead of just informing the user that something went wrong. As in "Here's the record that conflicted with the record you attempted to add. Do you want to keep the original or replace it?" instead of "Didn't work - Try again." Telling an end-user that the key already exists doesn't help. The user was trying to insert a WorkItem or an EmailContact or a Vehicle. Users don't know keys (or at least shouldn't have to).
 
I don't think a ThreadException handler is appropriate for data access-based exceptions, unless the exception itself is system-based, such as being unable to establich a connection, etc.
 
Writing the fewest lines of code possible shouldn't be the goal for a production application. Writing robust code that can actually deal with the problems it might face is difficult, but necessary if you want an application that will be easy to use.
 
I'm not meaning to be overly harsh, but I think exceptions and the rich information and recoverability they provide are underutilized. I have certainly been guilty of this. The method you propose here may suitable in some situations, such as small one-off tools that are not meant to be used by a large number of people, but I don't think it should be promoted for general use.
 
Charlie
 
if(!curlies){ return; }

GeneralRe: Sometimes a generic approach isn't suitable. Pinmemberfarukh ali farooq18:01 18 Jan '05  
GeneralRe: Sometimes a generic approach isn't suitable. Pinmemberextremeg9:19 2 Aug '06  
General[Message Removed] Pinmemberimmetoz9:35 1 Oct '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120528.1 | Last Updated 18 Jan 2005
Article Copyright 2005 by farukh ali farooq
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid