How to get the name of the method that caused the exception

There’s a TargetSite property on System.Exception that should come in handy.

Gets the method that throws the
current exception.

In your case, you probably want something like:

catch (Exception ex)
{
   MethodBase site = ex.TargetSite;
   string methodName = site == null ? null : site.Name;
   ...           
}

It’s worth pointing out some of the issues listed:

If the method that throws this
exception is not available and the
stack trace is not a null reference
(Nothing in Visual Basic), TargetSite
obtains the method from the stack
trace. If the stack trace is a null
reference, TargetSite also returns a
null reference.

Note: The TargetSite property may not
accurately report the name of the
method in which an exception was
thrown if the exception handler
handles an exception across
application domain boundaries.

You could use the StackTrace property as @leppie suggests too, but do note that this is a string representation of the frames on the stack; so you’ll have to manipulate if you only want the name of the method that threw the execption.

Leave a Comment