Get the name of the method that threw an exception

I recently had to dynamically retrieve the name of the method that had thrown an exception. It turns out that this is really easy to do using Exception.TargetSite.Name. Here is a passing NUnit test to illustrate:

[TestFixture]
public class ExceptionBehaviour {		
  [Test]
  public void TestGetMethodNameThrowingException() {
    try {
      new Something().MakeExceptionHappen();				
    } catch (Exception ex) {
      Assert.That(ex.TargetSite.Name, Is.EqualTo("MakeExceptionHappen"));
    }
  }
  private class Something {
    public void MakeExceptionHappen() {
      throw new NotImplementedException();
    }
  }
}

TargetSite returns a System.Reflection.MethodBase that has a number of interesting properties, like the type that threw the exception. Quite useful for logging.

Comments