首页 > 解决方案 > 有没有办法为任何 System.IndexOutOfRangeException 消息创建通用 EventHandler?

问题描述

对于一般的任何 UnhandledException 消息,我可以像这样创建一个新的 EventHandler:

程序.cs:

static void Main()
{
    Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException)
}

表格.cs:

Application.ThreadException += unhandledERROR;

void unhandledERROR(object sender, System.Threading.ThreadExceptionEventArgs e) 
{
    Console.WriteLine("ERROR Unhandled Exception");
}

当出现 System.IndexOutOfRangeException 消息时,还有一种方法可以设置通用 EventHandler 吗?

标签: c#

解决方案


您的代码不应包含任何IndexOutOfRangeException异常。真的不应该有未处理 IndexOutOfRangeException的异常。


正确的处理方式IndexOutOfRangeException是用trycatch在可能遇到的方法中。

try 
{
   // Code that can throw IndexOutOfRangeException 
} 
catch(IndexOutOfRangeException ex) 
{
  // Log, handle, etc.
}

在最后的处理程序中捕获异常为时已晚。


推荐阅读