.NET 控制台应用程序中的全局异常处理
控制台应用程序也需要一种机制来处理未处理的异常。虽然 ASP.NET 应用程序可以使用 global.asax,而 Windows 应用程序/服务可以使用 AppDomain 中的 UnhandledException 事件处理程序,但控制台应用程序采用略微不同的方法。
控制台应用程序的解决方案
在 .NET 中,为控制台应用程序定义全局异常处理程序的正确方法是使用 AppDomain 类的 UnhandledException 事件:
<code class="language-csharp">AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += MyExceptionHandler;</code>
这在 .NET 2.0 及更高版本中按预期工作。
针对 VB.NET 开发人员的说明
在 VB.NET 中,必须在 currentDomain 之前使用“AddHandler”关键字,否则 IntelliSense 中将看不到 UnhandledException 事件。语法上的差异源于 VB.NET 和 C# 如何处理事件处理。
示例
这是一个使用 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>
限制
需要注意的是,这种方法无法捕获在 Main() 方法开始运行之前由 JIT 编译器生成的类型和文件加载异常。要捕获这些异常,必须延迟 JIT 编译器,并将有风险的代码移到单独的方法中,并应用 [MethodImpl(MethodImplOptions.NoInlining)] 属性。
以上是如何在 .NET 控制台应用程序中实现全局异常处理程序?的详细内容。更多信息请关注PHP中文网其他相关文章!