Exception Management in .Net - Blogs

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

 #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("  Error: " + ErrorMessage);

             lock (thisLock)

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=””;       
     userid = Session["userid"].ToString();       
catch(Exception ex) 
     Response.Redirect("login.aspx", false);       

    Instead, use the following code to access session state information.

string  userid=””;
        userid = Session["userid"].ToString();
        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);
                       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("...");
    // some operation
     // handle the exception
    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

public class MyAppCustomException : Exception

public MyAppCustomException ()   
     : base() { }   

public MyAppCustomException (string strMessage)    
    : base(strMessage) { }  
public MyAppCustomException (string strMessage, Exception innerException)   
     : base(strMessage, innerException) { }   


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



Create a Windows Server 2012 R2 VM using ARM in Azure PowerShell

Hi Folks,In this Blog Post we will learn how to create an Azure ARM Virtual Machine using Azure Powe...

Read More >

Techno Feast 2014

Building enterprise apps with smart tools and solution...

Read More >

Introduction to DevOpSmartBoard

Azure DevOps is very famous devops platform in the current market. Azure DevOps provides end to end ...

Read More >

Migration Process of SVN to Git

Subversion (SVN) is a central version control system (VCS) while Git is a distributed version contro...

Read More >

Google Closure

IntroductionClosure is a collection of tools for building rich web applications in JavaScript.Google...

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 >

WScript Sleep- Exercise Desktop Remainder

Introduction - WScript.Sleep WScript.Sleep         ...

Read More >

MS Dynamics

Canarys team has built a few vertical solutions on Microsoft Dynamics platform. These products are b...

Read More >

Openbravo Services

We are happy to announce our newly acquired partnership with Openbravo, Spain. Openbravo is the prov...

Read More >

Canarys Automations Pvt Ltd recognized as finalist for 2017 Microsoft DevOps Partner of the Year Award

  Bengaluru, Karnataka, India — June 2, 2017 — Canarys Automations Pvt Ltd tod...

Read More >


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

Sign Up

  • Recent
  • Popular
  • Tag
Monthly Archive

Contact Us
  • *
  • *