在Windows窗体应用程序中捕获应用程序异常

时间:2011-06-09 11:17:29

标签: c# .net winforms exception-handling

无论如何都要抓住代码中任何地方引发的考验?我想捕获异常并以类似的方式处理它们,而不是为每个功能编写try catch块。

4 个答案:

答案 0 :(得分:37)

在Windows窗体应用程序中,当在应用程序中的任何位置(在主线程上或在异步调用期间)抛出异常时,您可以通过在Application上注册ThreadException事件来捕获它。通过这种方式,您可以以相同的方式处理所有异常。

Application.ThreadException += new ThreadExceptionEventHandler(MyCommonExceptionHandlingMethod);

private static void MyCommonExceptionHandlingMethod(object sender, ThreadExceptionEventArgs t)
{
    //Exception handling...
}

答案 1 :(得分:22)

我认为这是一个接近,因为你可以在win form应用程序中找到你想要的东西。

http://msdn.microsoft.com/en-us/library/ms157905.aspx

// Add the event handler for handling UI thread exceptions to the event.
Application.ThreadException += new ThreadExceptionEventHandler(ErrorHandlerForm.Form1_UIThreadException);

// Set the unhandled exception mode to force all Windows Forms errors to go through
// our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

// Add the event handler for handling non-UI thread exceptions to the event. 
AppDomain.CurrentDomain.UnhandledException +=
    new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

如果不执行所有这些步骤,您可能会遇到一些未处理的异常风险。

答案 2 :(得分:18)

显而易见的答案是将异常处理程序放在执行链的顶部。

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    try
    {
        Application.Run(new YourTopLevelForm());
    }
    catch
    {
        //Some last resort handler unware of the context of the actual exception
    }
}

这将捕获主GUI线程上发生的任何异常。如果您还希望全局捕获在所有线程上发生的异常,您可以订阅AppDomain.UnhandledException事件并在那里处理。

Application.ThreadException +=
    new ThreadExceptionEventHandler(MyCommonExceptionHandlingMethod)
private static void MyCommonExceptionHandlingMethod(
                                              object sender,
                                              ThreadExceptionEventArgs t)
{
    //Exception handling...
}

Charith J's answer

复制的代码

现在提出建议......

这些选项应该仅作为最后的手段使用,例如,如果您想要将无意中未捕获的异常从演示文稿中抑制到用户。当你知道关于异常情况的某些事情时,你应该尽可能早地抓住。更好的是,你可能能够解决这个问题。

结构化异常处理可能看起来像是一个不必要的开销,你可以解决所有问题,但它存在,因为事实并非如此。更重要的是,这项工作应该在编写代码时完成,而开发人员的逻辑则是新鲜的。不要懒惰,留下这项工作以供日后使用,或让一些更有影响力的开发人员接受。

如果您已经知道并且这样做,请道歉。

答案 3 :(得分:4)