简体   繁体   中英

How to get class and method name in the given scenario?

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.

Simply, you could use Exception TargetSite ;

catch(Exception ex)
{
    Console.WriteLine(ex.TargetSite.Name);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM