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.