AppDomain.FirstChanceException and stack overflow exception

前端 未结 7 1702

I\'m using the FirstChanceException event to log details about any thrown exceptions.

static void Main(string[] args)
{
    AppDomain.CurrentDomain.FirstChanceEx         


        
7条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-05 11:25

    Eventhough it is not a good way, in VB .NET you can prevent exception firing inside FirstChanceException event handler using "On Error Resume Next" statement, coming from VB 6. (I am not sure if C# has something similar) Additionally, you should prevent recursion on the event handler as mentioned here. Following is the sample code, seems to work as expected.

    Sub Main(args As String())
        AddHandler AppDomain.CurrentDomain.FirstChanceException, AddressOf FirstChanceExceptionEventHandler
        Throw New Exception("Exception thrown in main.")
    End Sub
    
    Private Sub FirstChanceExceptionEventHandler(ByVal source As Object, ByVal e As FirstChanceExceptionEventArgs)
        On Error Resume Next
    
        Dim frames As StackFrame() = New StackTrace(1).GetFrames()
        Dim currentMethod As MethodBase = MethodBase.GetCurrentMethod()
        If frames IsNot Nothing AndAlso frames.Any(Function(x) x.GetMethod() = currentMethod) Then
            Return
        Else
            Throw New Exception("Stackoverflow")
        End If
    End Sub
    

提交回复
热议问题