How to get the name of the function/sub?

pisceswzh

Well-known member
Joined
Mar 19, 2007
Messages
96
Programming Experience
1-3
Hi,

I am working on a project that need to send a bug report to the administrator whenever it happens. So I use a TRY...CATCH... to catch the bug and send an email to the administrator.

For the time being, I relize it by:

Class ClassLoad
 Private Sub subLoad()
  Try
   * codes
  Catch ex as Exception
   subSendEmail([Email Subject], [Email Body])
  End Catch
 End Sub
End Class

In the [Email Subject], I want it to be ClassName.SubName. Here it would be ClassLoad.subLoad.

In the [Email Body], I will use ex.message.

The problem is in the [Email Subject]. I don't know how to get the ClassName and the SubName. For the time being, I can only hardcode it. Is there a way to get the ClassName and the SubName using a variable or something?

Thanks!
 
You can get these in method with reflection:
VB.NET:
Dim classname As String = Me.GetType.FullName 'Name
Dim methodname As String = Reflection.MethodInfo.GetCurrentMethod.Name
Also useful if you have a common exception handler or using Application UnhandledException event is StackTrace class:
VB.NET:
Dim st As New StackTrace(e.Exception)
Dim methodname As String = st.GetFrame(0).GetMethod.Name
exception.ToString give you more information, including the Exception name and description, and the full StackTrace (method names, which method called which, and during debugging source file and line numbers)
 
Thanks JohnH!

I found another problem! I used your suggestion to try to get the line number of where it went wrong and found the

VB.NET:
New StackTrace(ex).GetFrame(0).GetFileLineNumber.ToString

always return a 0 in my cases.

Is there any place that I mistook?
 
Line numbers are only available if you initialize the StackTrace instance to gather this information, and only in debug mode of course.
 
Then how about get the function/sub name in a module?

Since in this case,

VB.NET:
Me.GetType.FullName

won't work.
 
Of course you can't reference "Me" current instance within a shared method, but the StackTrace method works there.
VB.NET:
st.GetFrame(0).GetMethod.ReflectedType.Name
You can also get it from
VB.NET:
Reflection.MethodInfo.GetCurrentMethod.ReflectedType.Name
 
Back
Top