#858 – Reading Exception Information in a Handler

When you catch an exception in a block of code that serves as an exception handler, you can read information about the error that occurred from an Exception object.  Every exception object will derive from the System.Exception class.  So, at a minimum, you’ll be able to access the properties of System.Exception.  (Not all properties will always contain values, however).

In the example below, the Bark method throws an exception of type System.Exception.  We query the System.Exception instance and dump out some of its values.

                try
                {
                    Dog d = new Dog("Kirby", 15);
                    d.Bark("Woof");
                }
                catch (System.Exception exc)
                {
                    Console.WriteLine(string.Format("Type = {0}", exc.GetType()));    // System.Exception
                    Console.WriteLine(string.Format("Message = {0}", exc.Message));   // Basic message
                    Console.WriteLine(string.Format("Source = {0}", exc.Source));     // Originating assembly
                    Console.WriteLine("Stack:");             // Dump out stack
                    Console.WriteLine(exc.StackTrace);
                }

Note that the call stack shows that Program.Main called Dog.Bark.
858-001

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #858 – Reading Exception Information in a Handler

  1. Pingback: Dew Drop – June 4, 2013 (#1,560) | Alvin Ashcraft's Morning Dew

  2. Pingback: #885 – Getting Information about the Method that Threw an Exception | 2,000 Things You Should Know About C#

Leave a comment