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

Implementing iOS Setting Bundle

 iOS Setting Bundle:-Actually sometimes we need to interact our app i.e giving some input value...

Read More >

New Tools in NAV 2013 (the less talked about ones) - Part 1

For some time now, I have been thinking about compiling on a list of new features and subtle tools i...

Read More >

Create custom project templates in Visual Studio

Visual studio installation comes with the various predefined project templates, and we can use one o...

Read More >

Creating a Simple Form with Validation Using ASP.NET MVC 4 Empty Template

There are multiple Validation attributes available in MVC. Validation attributes comes from System.C...

Read More >

Microsoft Azure : Machine Learning - Price Prediction

We'll create linear regression model that predicts price of automobile based on different variab...

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 >

Setup Jenkins for VSO with TFVC

Jenkins provides an easy-to-use Continuous Integration method, making it easier for developers to in...

Read More >

How to do Installation of K8S using kubeadm?

Till now I have given blogs on k8s objects, services, namespaces, ingress etc. but where to execute ...

Read More >

How to use AngularJS Services and Controllers

Here in this blog I am going to show some advanced and common functionalities of Angular JS which ca...

Read More >

Rapid Start Services in Microsoft Dynamics NAV 2013

RapidStart Services is an integrated tool that helps you to speed up the implementation process and ...

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
Text/HTML
Contact Us
  • *
  • *