控制台应用程序中的 .NET 全局异常处理程序

编程入门 行业动态 更新时间:2024-10-25 22:36:13
本文介绍了控制台应用程序中的 .NET 全局异常处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

Question: I want to define a global exception handler for unhandled exceptions in my console application. In asp, 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中,需要在currentDomain前加上AddHandler"关键字,否则IntelliSense中看不到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); } }

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

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 全局异常处理程序

本文发布于:2023-11-16 10:07:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1603319.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:控制台   全局   应用程序   异常   程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!