-2

I am using online c# compiler just to determine the class and method name.See the code given below, I am intentionally generating an error.

Expected Output is:

Hello, world!
ExceptionTest

, basically from where the exception has been generated.

OUTPUT, I m getting is

Hello, world!
System.Reflection.RuntimeMethodInfo 

//Rextester.Program.Main is the entry point for your code. Don't change it. //Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Diagnostics;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            try
            {
            //Your code goes here
            Console.WriteLine("Hello, world!");
             var abc = new Xyz();
            abc.ExTest();
            }
            catch(Exception ex)
            {
                Console.WriteLine(new StackTrace().GetFrame(1).GetMethod().DeclaringType.FullName);  

            }
        }
    }

    public class Xyz
    {
        public void ExTest()
        {
            var abc = new Abc();
            abc.ExceptionTest();
        }
    }

    public class Abc
    {
        public void ExceptionTest()
        {
            throw new Exception();

        }
    }
}

Please note, this is compiled on an online tool http://rextester.com/. I havent ran it on Visual Studio.

  • Next step would be to attach de debugger and see whether you got the right frame number. But this approach is very prone to errors if the code is ever going to be refactored. What is your use case? – Peter Bons Dec 25 '17 at 11:22
  • You are seeing the web site code calling your Main() method. At the catch clause, the stack is already unwound and any trace of the ExceptionTest method is lost. So it works the way you programmed it. Perhaps you meant to use the Exception.StackTrace property, it is not obvious from the question. – Hans Passant Dec 25 '17 at 11:39
  • If you want to explore stack trace of exception, then construct it like this: `new StackTrace(ex)` – Evk Dec 25 '17 at 12:06

1 Answers1

1

Simply, you could use Exception TargetSite;

catch(Exception ex)
{
    Console.WriteLine(ex.TargetSite.Name);
}
lucky
  • 12,734
  • 4
  • 24
  • 46