Mark's Stuff

My Foray Into Weblogging. Using this to store interesting items for later review.

Wednesday, May 23, 2007

Get Calling MethodName

A question came up in last night VB.Net User Group about how to get the calling method when using a common exception handling method. I remembered I did it somewhere before, but could not even remember any part of it to look up at the time. So I post it here and will send it to Sam for posting to the SIG blog.


Basically, you instantiate a System.Diagnostics.StackTrace object with the StackTrace from the Exception object, then get the MethodName from that. Here is an example using a Console app:



Imports System.Diagnostics
Imports system.reflection
Module Module1
  Sub Main()
    Try
      Throw New ApplicationException("HAHA")
    Catch ex As Exception
      ProcessException(ex)
    End Try
  End Sub

  Sub ProcessException(ByVal ex As Exception)
    Dim stackTrace As StackTrace = New StackTrace(ex)
    Dim stackFrame As StackFrame = stackTrace.GetFrame(0)
    Dim methodBase As MethodBase = stackFrame.GetMethod()
    Console.WriteLine("Error in Method {0} ", methodBase.Name)
  End Sub
End Module


Also, you can instantiate the StackTrace object without any arguments, and it loads the current method. You can then get the calling method (or the entire CallStack of methods) at any point in your code by walking through the StackFrames.



Imports System.Diagnostics
Imports system.reflection
Module Module1
  Sub Main()
    A()
  End Sub

  Sub A()
    B()
  End Sub

  Sub B()
    C()
  End Sub

  Sub C()
    Dim stackTrace As StackTrace = New StackTrace()
    Console.WriteLine("Called By Method {0} ", stackTrace.GetFrame(1).GetMethod().Name)
    Console.WriteLine("Listing the Entire Stack Trace:")
    For Each stackframe As StackFrame In stackTrace.GetFrames()
      Console.WriteLine("Method {0} ", stackframe.GetMethod().Name)
    Next
  End Sub
End Module

Labels: , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home