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.
JohnMarkHowell Twitter
Tweets by JohnMarkHowell-
Recent Posts
Archives
- August 2014
- July 2014
- January 2013
- December 2012
- November 2012
- August 2012
- July 2012
- June 2012
- May 2012
- March 2012
- February 2012
- January 2012
- December 2011
- August 2011
- June 2011
- February 2011
- January 2011
- December 2010
- October 2010
- September 2010
- July 2010
- May 2010
- December 2009
- September 2009
- August 2009
- July 2009
- March 2009
- January 2009
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- March 2008
- January 2008
- December 2007
- November 2007
- September 2007
- August 2007
- July 2007
- June 2007
- May 2007
- April 2007
- October 2006
- September 2006
- August 2006
- July 2006
- June 2006
- May 2006
- April 2006
- March 2006
- February 2006
- January 2006
- December 2005
- November 2005
- May 2005
Categories