Throwing Exceptions

Thursday, May 1, 2008 8:56 AM

I wanted to capture this in case I ever find myself trying to present this concept again and am failing to come up with a simple example that works. It's about exception handling in C#. I've known about this issue for quite some time and tried to present the problem to an internal user group where I work. Unfortunately the example I came up with didn't provide the expected result and we spent the whole presentation floundering around with the damn thing. Kudos to a buddy of mine for taking the time one weekend to come up with this working version (Thanks Paul).

Basically, when you catch exceptions, the way you re-throw them has a very important impact on the stack trace of the exception when it is caught later. Below is the code in its entirety. I'm mostly putting it here for reference, but would be glad to answer any questions you may have.

using System;

namespace ThrowSpike
{
   class Program
   {
      static void Main()
      {
         try
         {
            Console.WriteLine("ThrowOnly...");
            ThrowOnly();
         }
         catch (Exception ex)
         {
            Console.WriteLine(ex); // See a good stack trace
         }

         try
         {
            Console.WriteLine("ThrowCaughtException...");
            ThrowCaughtException();
         }
         catch (Exception ex)
         {
            Console.WriteLine(ex); // See an bad stack trace
         }
      }

      private static void ThrowOnly()
      {
         try
         {
            ThrowException();
         }
         catch
         {
            throw;
         }
      }

      private static void ThrowCaughtException()
      {
         try
         {
            ThrowException();
         }
         catch (Exception ex)
         {
            throw ex;
         }
      }

      private static void ThrowException()
      {
         throw new ApplicationException("This is a test");
      }
   }
}
Tags: .net