A tip about Error Handling

Tired of coding class names or method names in your error handling calls, then don’t!  .Net provides you a very convenient way to dynamically retrieve that information.  For example, a class with typical error handling might look something like this:
 
class TypicalErrorMessage
{
  private static readonly String _className = “TypicalErrorMessage”;
 
  public TypicalErrorMessage()
  {
  }
 
  public void MethodThatThrowsAnError()
  {
   String _memberName = “MethodThatThrowsAnError”;
 
   try
   {
         throw new System.Exception(“This is an error”);
   }
   catch (Exception ex)
   {
         MessageBox.Show(String.Format(“An error occurred in class {0} in member {1}.\nException: {2}”,
          _className, _memberName, ex.ToString()));
   }
  }
}
 
If you change the method name and forget to change the class or member name, then it gets confusing.  Also, it gets really tedious to create this type of error message for each member.  Rather than do the above, you can do something like the following:
 
class BetterErrorMessage
{
  public BetterErrorMessage()
  {
  }
 
  public void MethodThatThrowsAnError()
  {
   try
   {
         throw new System.Exception(“This is an error”);
   }
   catch (Exception ex)
   {
         MessageBox.Show(String.Format(“An error occurred in class {0} in member {1}.\nException: {2}”,
          this.GetType().ToString(), MethodBase.GetCurrentMethod(), ex.ToString()));
   }
  }
}
 
 
As you can see, you no longer have to enter the class or member names so you could copy and past this same error handling to another method without having to change the class or method names.
 
Note: this is not an example of how to do error handling, but how to get more specific information on the circumstances of the error.
 
This is just one quick example that shows how the .Net framework is built around making it easier to build better software faster.

Advertisements

About JohnMarkHowell

I am a professional software developer with over 20 years of experience. I currently specialize in Microsoft technologies such as VS, TFS, C#, VB.Net, WCF, WPF, WW, etc.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s