获取在catch中引起异常的调用方法

时间:2012-09-04 13:40:06

标签: .net vb.net

我正在Windows窗体的主入口点处理顶级异常。我想访问在我的处理程序中导致异常的调用方法/程序集。我有一种感觉,我将不得不使用跟踪,但我不知道在哪里。

Module Program
  Sub Main()
    Try
      AddHandler AppDomain.CurrentDomain.UnhandledException, Function(sender, e) ExceptionHandler.Handle(sender, DirectCast(e.ExceptionObject, Exception))
      AddHandler Application.ThreadException, Function(sender, e) ExceptionHandler.Handle(sender, e.Exception)
      Application.Run(ApplicationBase)
    Catch ex As Exception
      MessageBox.Show("Handled Exception")
    End Try
  End Sub
End Module

Public Class ApplicationBase
  Public Sub MethodA()
    'Causes an exception
    File.ReadAllLines("")
  End Sub
End Class

Public Class ExceptionHandler

  Public Shared Function Handle(sender As Object, e As Exception)
    Dim t As Type = sender.GetType()
    'Retrieve the calling method here?
    Dim callingMethod = "MethodA"
    Return True
  End Function

End Class

作为发送者的对象是一个线程,我试图看看这是否是调用导致异常的汇编/对象类型。

我的问题是如何获取方法名称/信息,如果可能的话,从“handle”方法中推送对象名称/程序集?

编辑:

虽然e.ToString()将提供方法名称 - 我正在寻找访问methodinfo /程序集的列表/导致异常的类型,如反射,然后我可以得到.DLL的版本号等等 - 我可能在这里做梦,但如果可能的话,我想知道这件事吗?

编辑2:

我尝试了e.TargetSite,其中MethodA()异常返回File.ReadAllLines()的方法信息我正在寻找导致异常的Class方法,因此方法信息将是MethodA - 尽管这更接近比我想象的还要多。

3 个答案:

答案 0 :(得分:2)

如果您想知道哪种方法引发了异常,您可以使用Exception.TargetSite属性;它返回MethodBase

  

如果抛出此异常的方法不可用且堆栈跟踪不是空引用(在Visual Basic中为Nothing),则TargetSite从堆栈跟踪中获取方法。如果堆栈跟踪是空引用,则TargetSite也返回空引用。

如果要在异常时遍历堆栈跟踪以在代码中找到一个方法(而不是库代码中的方法),则必须自己分析堆栈跟踪。

您可以获得异常的堆栈跟踪:

Dim stackTrace = new StackTrace(ex)

您可以通过索引获得单个堆栈帧:

Dim stackFrame = stackTrace.GetFrame(index)

您可以从堆栈框架中获取信息:

Dim method = stackFrame.GetMethod()

然后,您必须提出一种算法,该算法从上到下遍历堆栈跟踪,查找满足您要报告的堆栈帧条件的第一帧。这是一个非常简单的算法,可以找到执行程序集中的第一个框架。

Dim stackTrace = new StackTrace(ex)
Dim i As Integer
For i = 0 To stackTrace.FrameCount - 1
  Dim stackFrame = stackTrace.GetFrame(i)
  Dim method = stackFrame.GetMethod()
  If (method.DeclaringType.Assembly = Assembly.GetExecutingAssembly()) Then
    ' Found the method - do something and exit the loop
    Exit For
  End If
Next i

答案 1 :(得分:1)

e.ToString()将返回包括堆栈跟踪在内的完整详细信息。堆栈跟踪包括所有方法名称。

答案 2 :(得分:0)

[被修改]

看看How to format Exception's stack trace in C#?。使用带有异常的System.Diagnostics.StackTrace构造函数。