![]() |
General Programming »
Exception Handling »
General
Intermediate
Best Practices of Exception ManagementBy HandyGuyException management is one of the key areas for all kinds of application development . You should adopt an appropriate strategy for exception management to build high quality and robust applications. It is a very powerful concept and makes the development work very easy if it's used efficiently. |
C#, Windows, .NET, Visual Studio, Dev
|
|
Advanced Search Add to IE Search |
|
|
|
||||||||||||||||
Exception management is one of the key areas for all kinds of application development. You should adopt an appropriate strategy for exception management to build high quality and robust applications. It is a very powerful concept and makes the development work very easy if it's used efficiently. Inappropriate way of handling exceptions can degrade the performance of your applications.
Before dig into the details of exception management, it's very important to know what is an exception? The general meaning of "an exception is the breaching of a predefined assumption of the application". Remember, exception and error are not the same. To explain this, let me explain a couple of examples.
Let's say you are trying to log data to a file and your application assumes the file is present in the target path, but if it is not, then an exception would be raised. On the other hand, if your job is to trace the file and if it is present then log the data, in this scenario, raising an exception is a bad coding practice. It should be handled through validation code.
Let's say in a normal ASP.NET application, you are trying to update all necessary fields to the database, and your application assumes the database connection is available; suppose the connection is not available, then raising an exception is an ideal solution. On the other hand, while updating the mandatory fields in database and if a few of them are having null values, then raising an exception is not necessary, it should be handled through validation code.
As a developer, you must take advantage of the structured exception handling mechanism through try, catch and finally blocks. The .NET framework provides a broad hierarchy of exception classes to handle the different types of exceptions and all these classes are derived from Exception class (base class). The developer can extend the exception mechanism through inheritance, it helps to implement custom error handling or provides a proper gateway for complex error handling for the application. Unfortunately, many developers misuse this architecture capability. One very important thing you should keep in mind is how to react when an exception occurs at runtime. The good approach to react to an exception is:
catch blocks to catch the exception.
InnerException property of the Exception class. This allows the original exception to be wrapped inside a new exception (which is more relevant for your application). To understand the wrapping of exceptions, let's look at this example inside a method of your application which caught a lower level exception called IOException. You can wrap this original exception with an application level exception called LoadingException or FailtoLoadInfo or something else which is more relevant for your application, rather then alerting the lower level exception to the user. The exception management architecture of an application should have the capability to:
At the beginning of the design, you must plan for a consistent and robust exception management architecture and it should be well encapsulated and abstract the details of logging and reporting throughout all architecture layers of your application. Let's discuss some of the best practices of exception management.
The following list contains tips/suggestions to be considered while handling exceptions:
void EmpExits ( string EmpId)
{
//... search for employee
if ( dr.Read(EmpId) ==0 ) // no record found, ask to create
{
throw( new Exception("Emp Not found"));
}
}
The best practice is:
bool EmpExits ( string EmpId)
{
//... search for Product
if ( dr.Read(EmpId) ==0 ) // no record found, ask to create
{
return false}
}
}
try/catch block surrounding the loop.
try, catch and finally blocks. This is the recommended approach to handle exceptional error conditions in managed code, finally blocks ensure that resources are closed even in the event of exceptions. For example: SqlConnection conn = new SqlConnection("...");
try
{
conn.Open();
//.some operation
// ... some additional operations
}
catch(�)
{
// handle the exception
}
finally
{
if (conn.State==ConnectionState.Open)
conn.Close(); // closing the connection
}
double result = 0;
try{
result = firstVal/secondVal;
}
catch( System.Exception e){
//handling the zero divided exception
}
This is better then the above code:
double result = 0;
if(secondVal >0)
result = firstVal/secondVal;
else
result = System.Double.NaN;
throw to rethrow an existing exception is approximately the same as creating a new exception, and rethrowing an exception also makes it very difficult to debug the code. For example: try {
// Perform some operations ,in case of throw an exception�
} catch (Exception e) {
// Try to handle the exception with e
throw;
}
catch statements. This is nothing but ordering your exception from more specific to more generic. For example, to handle file related exceptions, it's better to catch FileNotFoundException, DirectoryNotFoundException, SecurityException, IOException, UnauthorizedAccessException, and at last Exception.
SqlException or OleDbException.
ConnectionState property for checking the connection availability instead of implementing an exception.
try/finally more often. finally provides option to close the connection or the using statement provides the same functionality.
SqlException or OleDbException, as below: try
{ ...
}
catch (SqlException sqlexp) // specific exception handler
{ ...
}
catch (Exception ex) // Generic exception handler
{ ...
}| You must Sign In to use this message board. | ||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 8 Mar 2005 Editor: Smitha Vijayan |
Copyright 2005 by HandyGuy Everything else Copyright © CodeProject, 1999-2009 Web22 | Advertise on the Code Project |