25Nov

Exception Management in .Net

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);

 

Related

Deploying an Outlook 2010 Add-in Using C#.NET And Visual Studio 2010

How to deploy an Outlook 2010 Add-in Using C#.NET And Visual Studio 2010In the previous blog, we wal...

Read More >

How to Customize the Microsoft Dynamics NAV 2013 R2 Splash screen Image

I think I got late with this post, but I was unaware that most of us still don’t know how to c...

Read More >

Performing Sonar Analysis for .NET projects

 Sonar Integration with TFS build for .net projectsThis document provides details about TFS and...

Read More >

Microsoft Azure Consultant

·         Executing technical feasibility as...

Read More >

Custom Control in WPF

File Upload Custom Control in WPFThis article is about Custom control in WPF, Custom controls are al...

Read More >

How to Install TestNG framework (Step by Step installation process)

Steps to Install Eclipse using install new Software:Step 1: In Eclipse, on top menu bar, Under Help ...

Read More >

A Brief History of Time (spent in the ERP marketplace)

Confession: This blog is no way connected to book titled "A Brief History of Time", author...

Read More >

M.S Dynamics Webinars Registration

h2{ margin-bottom:10px;}#wrapper{ margin: -40px auto 0; }#wrapper h1{ color:#FFF; text-align:center...

Read More >

Microsoft Azure : Running JAVA Web Application using template

We will create Java web app in Azure App Service by using the Azure portal. The Azure...

Read More >

Share

Post a Comment

  • Recent
  • Popular
  • Tag
Monthly Archive
Subscribe
Name

Contact Us
  • *
  • *