.NET Global exception handler in console application

后端 未结 5 1694
孤城傲影
孤城傲影 2020-11-22 12:01

Question: I want to define a global exception handler for unhandled exceptions in my console application. In asp.net, one can define one in global.asax, and in windows appli

5条回答
  •  再見小時候
    2020-11-22 12:21

    I just inherited an old VB.NET console application and needed to set up a Global Exception Handler. Since this question mentions VB.NET a few times and is tagged with VB.NET, but all the other answers here are in C#, I thought I would add the exact syntax for a VB.NET application as well.

    Public Sub Main()
        REM Set up Global Unhandled Exception Handler.
        AddHandler System.AppDomain.CurrentDomain.UnhandledException, AddressOf MyUnhandledExceptionEvent
    
        REM Do other stuff
    End Sub
    
    Public Sub MyUnhandledExceptionEvent(ByVal sender As Object, ByVal e As UnhandledExceptionEventArgs)
        REM Log Exception here and do whatever else is needed
    End Sub
    

    I used the REM comment marker instead of the single quote here because Stack Overflow seemed to handle the syntax highlighting a bit better with REM.

提交回复
热议问题