Global exception handling in .NET console applications
Console applications also need a mechanism to handle unhandled exceptions. While ASP.NET applications can use global.asax and Windows applications/services can use the UnhandledException event handler in the AppDomain, console applications take a slightly different approach.
Solution for console application
In .NET, the correct way to define a global exception handler for a console application is to use the UnhandledException event of the AppDomain class:
<code class="language-csharp">AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += MyExceptionHandler;</code>
This works as expected in .NET 2.0 and above.
Instructions for VB.NET Developers
In VB.NET, the "AddHandler" keyword must be used before currentDomain, otherwise the UnhandledException event will not be seen in IntelliSense. The difference in syntax stems from how VB.NET and C# handle event handling.
Example
Here is an example of global exception handling in a console application using C#:
<code class="language-csharp">using System; class Program { static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper; throw new Exception("发生异常"); } static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) { Console.WriteLine(e.ExceptionObject.ToString()); Console.WriteLine("按 Enter 键继续"); Console.ReadLine(); Environment.Exit(1); } }</code>
Restrictions
It is important to note that this approach cannot catch type and file loading exceptions generated by the JIT compiler before the Main() method starts running. To catch these exceptions, you must defer the JIT compiler and move the risky code into a separate method and apply the [MethodImpl(MethodImplOptions.NoInlining)] attribute.
The above is the detailed content of How to Implement a Global Exception Handler in .NET Console Applications?. For more information, please follow other related articles on the PHP Chinese website!