#885 – Getting Information about the Method that Threw an Exception

In an exception handler, you can use the TargetSite property of the Exception object to get information about the method that threw the exception.  This can be useful for diagnostics purposes, since you can get the name of the method, as well as the type and module where it was defined.

        static void Main(string[] args)
        {
            Console.WriteLine("About to do some stuff");

            try
            {
                DoSomeStuff();
            }
            catch (Exception xx)
            {
                Console.WriteLine("** Exception **");
                Console.WriteLine(xx);

                MethodBase originMethod = xx.TargetSite;

                Console.WriteLine("Exception origin info:");
                Console.WriteLine("  Method {0}", originMethod.Name);
                Console.WriteLine("  Defined in {0}", originMethod.DeclaringType);
                Console.WriteLine("  Type is {0}", originMethod.MemberType);
                Console.WriteLine("  Defined in {0}", originMethod.Module);
            }

            Console.ReadLine();
        }

        static void DoSomeStuff()
        {
            Dog d1 = new Dog("Jack", 15);
            d1.Bark(1000);
        }

885-001