.NET Global exception handler in console application

后端 未结 5 1651
孤城傲影
孤城傲影 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:39

    You also need to handle exceptions from threads:

    static void Main(string[] args) {
    Application.ThreadException += MYThreadHandler;
    }
    
    private void MYThreadHandler(object sender, Threading.ThreadExceptionEventArgs e)
    {
        Console.WriteLine(e.Exception.StackTrace);
    }
    

    Whoop, sorry that was for winforms, for any threads you're using in a console application you will have to enclose in a try/catch block. Background threads that encounter unhandled exceptions do not cause the application to end.

提交回复
热议问题