.NET Global exception handler in console application

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

    What you are trying should work according to the MSDN doc's for .Net 2.0. You could also try a try/catch right in main around your entry point for the console app.

    static void Main(string[] args)
    {
        try
        {
            // Start Working
        }
        catch (Exception ex)
        {
            // Output/Log Exception
        }
        finally
        {
            // Clean Up If Needed
        }
    }
    

    And now your catch will handle anything not caught (in the main thread). It can be graceful and even restart where it was if you want, or you can just let the app die and log the exception. You woul add a finally if you wanted to do any clean up. Each thread will require its own high level exception handling similar to the main.

    Edited to clarify the point about threads as pointed out by BlueMonkMN and shown in detail in his answer.

提交回复
热议问题