You know Exception management is one of the key areas and secure for all kinds of application development.
What is Exception Management?
Exception management involves managing exceptions that occur in runtime, because exceptions are expensive
What are the advantages of exception management?
Performance and Scalability: By knowing the causes of exceptions, and by writing code that avoids exceptions and that handles exceptions efficiently, you can improve the performance and scalability of application. Inappropriate way of handling exceptions can degrade the performance of your applications
Guide lines of exception management are as follows:
The exception management architecture of an application should have the capability to:
Log and report error information
Methods to avoid exceptions
Global.asax error handler
Use try, catch and finally blocks ,especially for disposing resources
Log and report error information
Catch the exceptions and store it in text file or database whatever the way developer want to implement it. So that it easy for developer or administrator to know where it is going wrong by seeing the log. In some cases application should report to the user, when user enters unexpected data. Developer can write the code in catch block to log the exception message. Check blow code snippet to store error log into text file.
FileStream fs = null;
string filePath = HttpContext.Current.Server.MapPath(“../Error_Log”);
string fileName = “Error” + DateTime.Now.ToString(“dd-MMM-yyyy”) + “.txt”;
string fullPath = Path.Combine(filePath, fileName);
#region Directory Creation
if (!Directory.Exists(filePath))
Directory.CreateDirectory(filePath);
#endregion
#region Logg Error
using (fs = new FileStream(fullPath, FileMode.Append))
{
thisLock = new Object();
sWriter = new StreamWriter(fs);
sb = new StringBuilder();
sb.Append(“[” + DateTime.Now.ToString(“dd/MMM/yyyy 'at' HH:MM:ss tt”));
sb.Append(” ] “);
sb.Append(“==>”);
sb.Append(” Error: ” + ErrorMessage);
sb.Append(Environment.NewLine);
lock (thisLock)
{
sWriter.Write(sb.ToString());
sWriter.Flush();
sWriter.Close();
}
}
#endregion
Methods to avoid exceptions
Avoid exception handling inside loops. If it's really necessary, implement try/catch block surrounding the loop.
Check for null values
string userid=””;
try
{
userid = Session[“userid”].ToString();
}
catch(Exception ex)
{
Response.Redirect(“login.aspx”, false);
}
finally
{
}
Instead, use the following code to access session state information.
string userid=””;
if(Session[“userid”]!=null)
userid = Session[“userid”].ToString();
else
Response.Redirect(“login.aspx”, false);
Global.asax error handler
Implementing a global error handler handles all unhandled exceptions in your application. This is the first step to implement exceptions management. Use the Application_Error event in Global.asax code behind file like below
protected void Application_Error(object sender, EventArgs e)
{
if (Server.GetLastError() != null)
{
Exception objErr = Server.GetLastError().GetBaseException();
if ( objErr != null)
{
Utilities.clsLogger.LOG(“application”, “”, “”, “”, objErr.Message);
Server.ClearError();
objErr = null;
Response.Redirect(“ErrorPage.aspx”, false);
}
}
}
Use try, catch and finally blocks ,especially for disposing resources
Adopt the standard way of handling exceptions, through 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.
SqlConnection conn = new SqlConnection(“…”);
try
{
conn.Open();
// some operation
}
catch(…)
{
// handle the exception
}
finally
{
if (conn.State==ConnectionState.Open)
conn.Close(); // closing the connection
}
I would like to explain custom exceptions also-
What are custom exceptions?
Custom exceptions are exceptions which created by developer, derives from the System.Exception class and allows you to make specific Exceptions with customized messages. This gives more useful information when your application fails; you can also track back the original error message.
Example code to define custom exception class and throw custom exception
[Serializable]
public class MyAppCustomException : Exception
{
public MyAppCustomException ()
: base() { }
public MyAppCustomException (string strMessage)
: base(strMessage) { }
public MyAppCustomException (string strMessage, Exception innerException)
: base(strMessage, innerException) { }
}
Example:
// Throw exception without message
throw new MyAppCustomException ();
// Throw exception with message :
throw new MyAppCustomException (strMessage);
// Throw exception with message and inner exception
throw new MyAppCustomException (strMessage, innerException);