user3265040
user3265040

Reputation: 315

Pass the class name/method name in argument, possible?

I've made a method that logs an exception into a folder called Logs and save it in the text file. The format of the text output is like so:

Main thread has thrown an exception @ ClassName::MethodName : Exception.ToString();

ClassName::MethodName is a text that should contain which class and which method throws it (while doing the task). How is it possible to pass those arguments? For example, if I have a class named "Test", and I have this method:

public void DoSomething() {
    try {
        this.Name = "Test";
    } catch (Exception e) {
        MainForm.Instance.LogException(e);
    }

Then if an exception was thrown, the arguments Test::DoSomething will be passed and shown. How is it possible to do it in C#?

Upvotes: 1

Views: 613

Answers (4)

Toan Nguyen
Toan Nguyen

Reputation: 11601

You can use the code below:

 public static void DoSomething()
        {
            try
            {
                throw new InvalidOperationException("Exception");
            }
            catch (Exception e)
            {
                StackTrace stackTrace = new StackTrace();

                StackFrame stackFrame = stackTrace.GetFrame(0);

                Console.WriteLine("Class Name: {0}, Method Name: {1}", stackFrame.GetMethod().Module, stackFrame.GetMethod().Name);


            }
        }

Upvotes: 1

Karthik Kalyanasundaram
Karthik Kalyanasundaram

Reputation: 1525

e.StackTrace.GetFrame(0) will give you the most recent StackFrame.

Given that, e.StackTrace.GetFrame(0).GetMethod() will give you an instance of MethodBase, from this instance, you can get the method name and class

Upvotes: 0

d.moncada
d.moncada

Reputation: 17402

You could use Reflection..

public void DoSomething() {
    try {
        this.Name = "Test";
    } catch (Exception e) {
        var method = System.Reflection.MethodBase.GetCurrentMethod();
        var methodName = method.Name;
        var className = method.ReflectedType.Name;
        MainForm.Instance.LogException(String.Format("{0} - {1}:{2}", className, methodName, e));
    }

Upvotes: 2

rerun
rerun

Reputation: 25505

The exception has a StackTrace property which gives you as much information as possible as to where the exception was thrown.

Upvotes: 1

Related Questions