代码很简单,如下
Module Module1
Public Sub ReportPosition(ByVal msg As String)
Dim strace As New StackTrace(True)
Dim frame As New StackFrame
frame = strace.GetFrame(1) '0表示调用堆栈的最里层(本函数),1表示上一层也就是调用ReportPosition()的函数,
MsgBox("错误信息:" & msg & ControlChars.CrLf & "位置:" & frame.ToString)
'可以将frame.ToString()的内容保存到文件
'在trycatch中调用该方法可以方便跟踪异常位置
End Sub
End Module
'调用
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
'do something
Dim i As Int32 = 0
i = 1 / i
Catch ex As Exception
ReportPosition(ex.Message)
End Try
End Sub
Public Sub ReportPosition(ByVal msg As String)
Dim strace As New StackTrace(True)
Dim frame As New StackFrame
frame = strace.GetFrame(1) '0表示调用堆栈的最里层(本函数),1表示上一层也就是调用ReportPosition()的函数,
MsgBox("错误信息:" & msg & ControlChars.CrLf & "位置:" & frame.ToString)
'可以将frame.ToString()的内容保存到文件
'在trycatch中调用该方法可以方便跟踪异常位置
End Sub
End Module
'调用
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
'do something
Dim i As Int32 = 0
i = 1 / i
Catch ex As Exception
ReportPosition(ex.Message)
End Try
End Sub
不过只有在Debug模式并且有.pdb文件的情况下才能获得调用函数的所在的文件和行号。
刚才看下面的文章想到的
Find out what's closing your application
他的代码如下:
Private Sub Form1_Closing(ByVal sender As Object, _
ByVal e As System.ComponentModel.CancelEventArgs) _
Handles MyBase.Closing
Dim O As System.Diagnostics.StackTrace = _
New System.Diagnostics.StackTrace(True)
Dim F As System.Diagnostics.StackFrame
F = O.GetFrame(7)
Select Case F.GetMethod.Name.ToString
Case "SendMessage"
MsgBox("Closing because of call in code.")
Case "CallWindowProc"
MsgBox("Closing because of system menu click.")
Case "DispatchMessageW"
MsgBox("Closing because of Task Manager.")
Case Else
MsgBox("Don't Know why I'm closing!!??")
End Select
End Sub
ByVal e As System.ComponentModel.CancelEventArgs) _
Handles MyBase.Closing
Dim O As System.Diagnostics.StackTrace = _
New System.Diagnostics.StackTrace(True)
Dim F As System.Diagnostics.StackFrame
F = O.GetFrame(7)
Select Case F.GetMethod.Name.ToString
Case "SendMessage"
MsgBox("Closing because of call in code.")
Case "CallWindowProc"
MsgBox("Closing because of system menu click.")
Case "DispatchMessageW"
MsgBox("Closing because of Task Manager.")
Case Else
MsgBox("Don't Know why I'm closing!!??")
End Select
End Sub