.NET控制台应用程序中的全局异常处理 [英] .NET Global exception handler in console application

查看:250
本文介绍了.NET控制台应用程序中的全局异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但是如何为控制台应用程序定义全局异常处理程序?

currentDomain似乎不起作用(.NET 2.0)?



编辑:



Argh,愚蠢的错误。

在VB.NET中,需要在currentDomain之前添加AddHandler关键字,否则在IntelliSense中看不到UnhandledException事件。 ..

这是因为VB.NET和C#编译器不同地处理事件处理。

解决方案

否这是正确的方法。这可以正常工作,或许您可以从中工作:

  using System; 

类程序{
static void Main(string [] args){
System.AppDomain.CurrentDomain.UnhandledException + = UnhandledExceptionTrapper;
抛出新的异常(Kaboom);
}

static void UnhandledExceptionTrapper(object sender,UnhandledExceptionEventArgs e){
Console.WriteLine(e.ExceptionObject.ToString());
Console.WriteLine(按Enter继续);
Console.ReadLine();
Environment.Exit(1);
}
}

请记住,您无法捕获类型和文件通过抖动产生的异常负载异常。它们发生在您的Main()方法开始运行之前。捕捉这些需要延迟抖动,将风险代码移动到另一种方法中,并将[MethodImpl(MethodImplOptions.NoInlining)]属性应用到它。


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);

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.

解决方案

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);
    }
}

Do keep in mind that you cannot catch type and file load exceptions generated by the jitter this way. They happen before your Main() method starts running. Catching those requires delaying the jitter, move the risky code into another method and apply the [MethodImpl(MethodImplOptions.NoInlining)] attribute to it.

这篇关于.NET控制台应用程序中的全局异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆