Best Practices for handling exceptions:
This article shall explain some of the best practices when you deal with exceptions.
Exception is an expensive process, for this reason, you should use exceptions only in exceptional situations and not to control regular logic flow.
For example:
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
}
}
Avoid exception handling inside loops, if its really necessary implement try/catch block surrounds the loop.
Adopt the standard way of handling the exception through try, catch and finally block. 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
}
Where ever possible use validation code to avoid unnecessary exceptions .If you know that a specific avoidable condition can happen, precisely write code to avoid it. For example, before performing any operations checking for null before an object/variable can significantly increase performance by avoiding exceptions.
For example:
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;
Do not rethrow exception for unnecessary reason because cost of using throw to rethrow an existing exception is approximately the same as creating a new exception and rethrow exception also makes 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;
}
The recommended way to handle different error in different way by implement series of catch statements this is nothing but ordering your exception from more specific to more generic for example to handle file related exception its better to catch FileNotFoundException, DirectoryNotFoundException, SecurityException, IOException, UnauthorizedAccessException and at last Exception.
.NET errors should be capture through SqlException or OleDbException.
- Use the ConnectionState property for checking the connection availability instead of implementing an exception.
- Use Try/Finally more often, finally provides option to close the connection or the using statement provides the same functionality.
- Use the specific handler to capture specific exception, in few scenarios if you know that there is possibility for a specific error like database related error it can be catch through SqlException or OleDbException as below.
try
{ ...
}
catch (SqlException sqlexp) // specific exception handler
{ ...
}
catch (Exception ex) // Generic exception handler
{ ...
}
Its recommend to use "Exception Management Application Block" provided by Microsoft. It is a simple and extensible framework for logging exception information to the event log or you can customize to write the exception information to other data sources without affecting your application code and implemented all best practices and tested in Microsoft Lab.