#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.

                    Dog d = new Dog("Kirby", 15);
                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

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