在控制台应用程序.NET全局异常处理程序 [英] .NET Global exception handler in console application
问题描述
问:我想定义一个全局异常处理程序在我的控制台应用程序中未处理的异常。在asp.net中,可以定义一个在Global.asax中,并在Windows应用/服务,可以定义如下
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 applications /services, one can define as below
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyExceptionHandler);
但我怎么可以定义一个全局异常处理程序的控制台应用程序?
currentDomain似乎不工作(.NET 2.0)?
But how can I define a global exception handler for a console application ?
currentDomain seems not to work (.NET 2.0) ?
编辑:
哎呀,愚蠢的错误。
在VB.NET中,需要添加的AddHandler关键字currentDomain前面,否则一个不看UnhandledException事件智能感知...
这是因为VB.NET和C#编译器对待事件的处理有所不同。
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.
推荐答案
没有,这是做了正确的方法。这个工作正是因为它应该是你可以或许工作:
No, that's the correct way to do it. This worked exactly as it should, something you can work from perhaps:
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);
}
}
这篇关于在控制台应用程序.NET全局异常处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!