Home > Articles > Programming > Windows Programming

This chapter is from the book

Recording an error message does not necessarily have to be fast. I am not saying you should ignore sound design practices and provide a sloppy means of error logging. What I am saying is that your exception handling should concentrate on providing the best options for recording errors and not necessarily the fastest means of handling them. When an application fails and it begins to throw exceptions, its performance takes a back seat to that of dealing with the error itself. This is not always the case, because there are systems that require fast failing. However, the majority of the systems I have built required that the framework allow the best means of solving the problem. The first and best option for solving the problem is discovering what the problem is. Unless you are the user of the application, this may not be possible without a log and/or tracing mechanism.

Logging allows anyone to read the state of the system at any time. One of the best places to log is in the exception class itself because the exception has the necessary information to record. Logging can be done in one shot, usually in the final catch block of what could be multiple levels of exception handlers. Another option is to log in real time. Real-time logging is the recording of information while the system is running. This is also referred to as tracing. This helps eliminate the more difficult runtime problems that may occur and that one-time logging may not help to solve. The trick is to capture as much information as possible in the one-time log event so that tracing isn't always necessary in production. Why? Aside from slowing down performance (which you can minimize, as we will see), tracing forces the developer periodically to add tracing function throughout the code, thus cluttering it up. Before we go into how you can architect a robust and flexible tracing system, let's first show how we can build one-time logging into our exception handling.

You saw in the FtpException example how the user had the option of logging by passing in true as the last parameter (bLog). However, all of this functionality was passed onto the base class. Because logging usually conforms to a universal standard in your architecture, this can be implemented in your base exception handling class, as shown below:

Listing 2.3 The beginning of a real base exception class.

public class BaseException : System.ApplicationException

   private int m_nCode;

   public BaseException(){;}

   public BaseException(string sMessage, bool bLog) : this(sMessage,
         null, bLog){;}

   public BaseException(string sMessage, System.Exception
         oInnerException, bool bLog) : this(null, 0, sMessage,
         oInnerException, bLog){;}

   public BaseException(object oSource, int nCode, string sMessage,
         bool bLog) : this(oSource, nCode, sMessage, null,          bLog){;}

   public BaseException(object oSource, int nCode, string sMessage,
         System.Exception oInnerException, bool bLog) :
         base(sMessage, oInnerException)
         if (oSource != null)
                     base.Source = oSource.ToString();
         Code = nCode;

         // need to add logic to check what log destination we
         // should logging to e.g. file, eventlog, database, remote
         // debugger
         if (bLog)
               // trace listeners should already initialized, this
               // is called to be prudent

              // log it
              Dump(Format(oSource, nCode, sMessage,

   /// <summary>
   /// Writes the entire message to all trace listeners including
   /// the event log
   /// </summary>
   /// <param name="oSource"></param>
   /// <param name="nCode"></param>
   /// <param name="sMessage"></param>
   /// <param name="oInnerException"></param>
   private void Dump(string sMessage)
         // write to all trace listeners
         Trace.WriteLineIf(Config.TraceLevel.TraceError, sMessage);

         // see Utilities.InitTraceListeners()
         // record it to the event log if error tracing is on
         // The EventLog trace listener wasn't added to the
         // collection to prevent further traces
         // from being sent to the event log to avoid filling up the
         // eventlog
         if (Config.TraceLevel.TraceError)
               EventLog.WriteEntry("PMException", sMessage);

   public static string Format(object oSource, int nCode, string
                     sMessage, System.Exception oInnerException)
         StringBuilder sNewMessage = new StringBuilder();
         string sErrorStack = null;

         // get the error stack, if InnerException is null,
         // sErrorStack will be "exception was not chained" and
         // should never be null
         sErrorStack = BuildErrorStack(oInnerException);

         // we want immediate gradification
         Trace.AutoFlush = true;

         sNewMessage.Append("Exception Summary \n")
                    .Append(" - ")

         return sNewMessage.ToString();

   /// <summary>
   /// Takes a first nested exception object and builds a error
   /// stack from its chained contents
   /// </summary>
   /// <param name="oChainedException"></param>
   /// <returns></returns>
   private static string BuildErrorStack(System.Exception
         string sErrorStack = null;
         StringBuilder sbErrorStack = new StringBuilder();
         int nErrStackNum = 1;
         System.Exception oInnerException = null;

         if (oChainedException != null)
               sbErrorStack.Append("Error Stack \n")

               oInnerException = oChainedException;
               while (oInnerException != null)
                                 .Append(") ")

                     oInnerException =


                           .Append("Call Stack\n")

               sErrorStack = sbErrorStack.ToString();
               sErrorStack = "exception was not chained";

          return sErrorStack;

   public int Code
         get {return m_nCode;}
         set {m_nCode = value;}

The logging logic in Listing 2.3 is simple. When throwing an exception, the developer has the option of logging by passing in true for the log flag, as shown in this FTP client code snippet:

Listing 2.4 Applying our base exception child class.

FtpWebResponse = FtpWebResponse.Create(ControlStreamReader);
         // success  - 200
         // this reply is ok
   case Constants.NOT_LOGGED_IN_CODE:
         throw new FtpException (this, FtpWebResponse.Code,
               FtpWebResponse.GetOriginalMessage(), false);
   throw new FtpException (this, FtpWebResponse.Code,
   NotValidReplyCodeMessage(FtpWebResponse.Code, "PORT"),
   true); // log this error!!!!!

Here I show a custom FTP exception class passing in the response code, an appropriately returned code description, and the source of the error. In the default section of the switch case statement, the developer wishes to log this exception. In the case statement directly above the default, the FtpException (for whatever reason) does not log. This is an imaginary scenario, but it quickly shows how to specify which exceptions are logged and which ones aren't. The logging itself is handled by the exception, as we have seen. But where does the error actually get logged?

Challenge 2.2

How can you globally control where logging output is sent?

A solution appears in the next section.

Determining Where to Log (Using the Trace Object)

In the BaseException class, logging output is eventually written to one or more log targets using the statement Trace.WriteLineIf(). Here I use the tracing capabilities of the FCL to determine where to send the output. You can easily write to the Windows event log, a log file, or another target directly but I wanted to leverage what I consider one of the more elegant features of .NET—tracing.

// write to all trace listeners
Trace.WriteLineIf(Config.TraceLevel.TraceError, sMessage);

The .NET Trace class methods can be used to instrument any debug or release build of your application. Tracing can be used to monitor the health of any system during runtime but it can also act as logging mechanism. Whether you use it for logging, monitoring, or both, tracing can be great way to diagnose problems without affecting or even recompiling your application.

The Trace.WriteLineIf method above takes only two arguments. The first is a boolean parameter where I use what is called a TraceSwitch to determine whether I want to trace a message and at what level. Don't worry about the TraceSwitch just yet if you haven't worked with them; I will explain them in the upcoming technology backgrounder. The second parameter is simply the message I want to trace. Trace.WriteLineIf() is called from within the Dump method. The Dump method is, in turn, called from within the overloaded BaseException constructor.

Listing 2.5 Sample Base Exception logging routine.

       if (bLog)
             // trace listeners should already initialized, this
             // is called to be prudent

             // log it
             Dump(Format(oSource, nCode, sMessage,

You'll also notice a few other goodies in the BaseException class. In Listing 2.5, you see that the Dump method calls the Format method. This method is used to prepare the output format of the error message. How you format your messages and what information is included is completely design-specific. Here my formatted message prepares a string that includes three main parts. The first part is the source of the error, usually passed in as this so that I can access the fully qualified type as well as other elements of the calling object. The second part is the error code that will be ultimately included in the recorded message. The third part is an error summary, which is the description of the error provided by the thrower. This is one set in the exception thrown that will actually be logged. The final parameter is the chained exception, which is usually the one just caught. This will be used to build our error stack because it will contain any previously caught and chained errors. The .NET framework provides the mechanism to chain and even a stack trace to use but it does not provide a formatted error stack. This is your job. Providing a full error stack each time you log is optional but it will help determine the cause of the error. This is in case the high-level error does not provide enough clues as to the cause. In fact, I'm sure you have already found that it typically doesn't.

Determining What to Log

Provide Enough Information

When building your application exception classes, especially your base exception class, you will need to determine how much information to provide. Determining this completely depends on the audience. When providing error information to users, you want to give them enough information to determine that there is a problem without inundating them with terse language or technical details that they may not understand. However, this does not mean you forgo technical information as part of your exception. This only means you do not want to display it by default. For example, when displaying an error dialog, you should show only a high-level version of the problem. Optionally, you can also add a Details button to allow the more technically savvy user get more detailed error information if he or she so chooses. You want to provide the option of information without intimidation.

Providing a high-level error description is typically the job of the last handler of the exception. This is referred to as the exception boundary. This could be an ASP.NET page or a GUI catching the final exception and displaying it to the user. Again, this does not in any way mean you forgo providing rich information; in fact, you should side on providing more rather than too little. Just hide the complexity from the user. One of the great things about .NET is that you don't have to provide rich information through extensive custom development. The FCL takes care of providing you with helper objects and methods that will give you as much relevant data as you can handle. The following table shows some of the informational items you can easily access using the FCL:

Table 2.1. Environmental information: Some examples of information providers from the FCL



Dates and Times


Source of Exception


Type of Exception


Exception Message


Current Method


Machine Name

Environment.MachineName or Dns.GetHostName

Current IP


Call Stack

Exception.StackTrace or Environment.StackTrace

OS Information


Application Domain


Current Assembly


Root Error Cause


Chained Exception


Assembly Version

Included in AssemblyName.FullName

Thread ID


Thread User


You'll notice in Table 2.1 that a couple of the items are retrieved using .NET Reflection. Reflection services allow you introspect the public members of almost any class, including the System.Exception class. This can come in very handy when displaying detailed information during logging or display and should be explored. For more information on Reflection services, please refer to the technology backgrounder on Reflection in Chapter 4.

Building an Error Stack

One of the first things I typically provide is an error stack. This is not to be confused with a call stack; something the System.Exception class provides “out of the box.” As mentioned earlier, the error stack is built around another nice feature of .NET called exception chaining. This is actually a well-known design pattern that the .NET System.Exception class provides for free. All you have to do is take advantage of it. This means making sure during each throw of your BaseException that you pass in the exception class initially caught, as in the following snippet:

catch(FtpException ftpe)
      throw new BaseException(this, 1234, "FTP Error: " +
                  ftpe.Message, ftpe, true);

Here I am throwing a new exception, passing in a source object (this), an error code (1234), an error description, and what is now the inner exception. In this case, that inner exception is an FtpException. The last parameter (true) will tell this exception to log itself. This will eventually lead to the BuildErrorStack method being called. This is the heart of this method. The BuildErrorStack method simply loops through each chained exception, using the inner exception property of the BaseException class, as shown in Listing 2.6. The format and additional items you place here are, again, up to you. The point is that you leverage the FCL chaining facility by building a useful display medium that will hopefully help solve the issue.

Listing 2.6 Sample stack builder used in our base exception class.

if (oChainedException != null)
      sbErrorStack.Append("Error Stack \n")

      oInnerException = oChainedException;
      while (oInnerException != null)
                        .Append(") ")

            oInnerException =


                  .Append("Call Stack\n")

      sErrorStack = sbErrorStack.ToString();


Challenge 2.3

When throwing exceptions from Web services, what other steps are required? How does SOAP affect exception handling?

A solution appears in the upcoming technology backgrounder on SOAP Faults (page 65).

Throwing System Exceptions

Once you've built your base exception class and all of its helpers, you are probably going to want to leverage it as much as possible. That said, you may also want to take advantage of some of the system exception classes (e.g., System.IOException) that the FCL has to offer. How does one leverage the features of both? The answer is that you use both by employing exception wrapping. When you want to throw a system exception and still want to take advantage of your base exception features, you simply create a new system exception class and pass that as the inner exception of your base exception class constructor. This in effect “wraps” the system exception, allowing it to appear neatly as part of your error stack. This can all be with one (albeit long) line of code:

throw new BaseException(this, 120, GetMessage(120),
new System.IOException(), true);

Here I want to throw the system exception IOException. However, I still want to use my BaseException class features, such as error stacks, message formatting, and logging. Using exception wrapping, I get both.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020