Home >Backend Development >C++ >How to Implement a Global Exception Handler in .NET Console Applications?

How to Implement a Global Exception Handler in .NET Console Applications?

Barbara Streisand
Barbara StreisandOriginal
2025-01-24 08:06:11956browse

How to Implement a Global Exception Handler in .NET Console Applications?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn