Exception Management in .Net - Blogs
X
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

Using Bootstrap Validation in Asp.net Applications

Bootstrap is a powerful mobile first front-end framework for faster and easier web development. It u...

Read More >

Prerequistes for installing TestNG Framework in eclipse IDE

TestNG Introduction TestNG is an open source automated testing framework, where NG of Test...

Read More >

Object Identification and Object Repositories in QTP

Object IdentificationQTP performs the operation only after identifying the object uniquely. In order...

Read More >

How to Remove the Departments Action Button in NAV 2015

Some customers may not want to use Departments menu available. We need to have some option to remove...

Read More >

Microsoft VSTS Consulting

At a time when businesses are attempting to attain the highest possible degree of standardization an...

Read More >

Intro to Git and GitHub and Difference

Let us check what is Git and GitHub and how they work. To understand this, let us imagine a scenario...

Read More >

Supercharging GitHub Actions with Job Summaries and Pull Request comments

A new feature on GitHub allows you to write job descriptions for your actions with Job Summaries and...

Read More >

Web API 2 With Repository pattern

Web API 2 With Repository patternHow to create Repository pattern in web API 2.Overview of Repositor...

Read More >

Extent Reports in Selenium CSharp (C#)

Reports play a fundamental role when it comes to TESTING. Tester can now  know the real-time r...

Read More >

Azure Consulting Service

We are Microsoft Cloud Solution Providers (CSP) Canarys helps you achieve higher productivity, ...

Read More >

Share

Try DevOpSmartBoard Ultimate complete Azure DevOps End-to end reporting tool

Sign Up

  • Recent
  • Popular
  • Tag
Monthly Archive
Subscribe
Name

Text/HTML
Contact Us
  • *
  • *