问题:我想为控制台应用程序中未处理的异常定义一个全局异常处理程序.在asp.net,可以在全局中定义一个.在windows应用程序/服务中,可以定义如下

AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyExceptionHandler);

But how can I define a global exception handler for a console application ?
currentDomain seems not to work (.NET 2.0) ?

Edit:

Argh, stupid mistake.
In VB.NET, one needs to add the "AddHandler" keyword in front of currentDomain, or else one doesn't see the UnhandledException event in IntelliSense...
That's because the VB.NET and C# compilers treat event handling differently.

推荐答案

不,这是正确的方法.这正是它应该发挥的作用,也许你可以从中受益:

using System;

class Program {
    static void Main(string[] args) {
        System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
        throw new Exception("Kaboom");
    }

    static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) {
        Console.WriteLine(e.ExceptionObject.ToString());
        Console.WriteLine("Press Enter to continue");
        Console.ReadLine();
        Environment.Exit(1);
    }
}

请记住,您不能以这种方式捕获由抖动生成的类型和文件加载异常.它们发生在main()方法开始运行之前.捕捉这些需要延迟抖动,将有风险的代码移到另一个方法中,并对其应用[MethodImpl(MethodImplOptions.NoInlining)]属性.

.net相关问答推荐

.NET Blazor-使用子组件中的处理程序方法进行双向数据绑定

AutoMapper在实体框架查询后不知从哪里带来数据

如何从 tshark 的 stderr 捕获实时数据包计数?

.NET MAUI ListView - ObservableCollection - 在异步方法期间不更新

Visual Studio 2022 中的目标操作系统和目标运行时有什么区别?

如何找到windows服务exe路径

SetupSet() 已过时.代替什么?

根源是什么?

我可以从 .NET/C# 获取其他进程的命令行参数吗?

将 Topshelf 应用程序安装为 Windows 服务

为什么 WCF 中不允许方法重载?

如何退出所有正在运行的线程?

软件包版本始终为 1.0.0,带有 dotnet pack

.NET Framework SDK 和 Targeting 包有什么区别

如何仅在需要时提升权限?

用 double 替换 int 时的 Visual Studio 长编译

将月份 int 转换为月份名称

如何获取命名空间中的所有类?

清除文件内容

在 .NET 中乘以时间跨度