有没有一种方法可以为任何System.IndexOutOfRangeException消息创建常规EventHandler?

时间:2019-10-27 18:57:31

标签: c#

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

Program.cs:

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

Form.cs:

Application.ThreadException += unhandledERROR;

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

当System.IndexOutOfRangeException消息出现时,还有一种方法来设置常规EventHandler吗?

1 个答案:

答案 0 :(得分:0)

您的代码不应包含IndexOutOfRangeException个异常。确实应该没有未处理 IndexOutOfRangeException例外。


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

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

在万不得已的处理程序中捕获异常为时已晚。