【问题标题】:Unhandled Exceptions thrown in threads are not caught [duplicate]未捕获线程中抛出的未处理异常[重复]
【发布时间】:2013-06-16 16:48:39
【问题描述】:

我正在开发一个使用普通 threads 实现的项目。应用程序中的大多数预期异常都得到了处理,但是,在某些情况下,其中一个线程抛出了一个意外的异常,应用程序就崩溃了(应用程序是基于 I/OClient-Server 所以几乎不可能处理所有例外)。

为了解决这个问题,我尝试定义一个全局UnhandledExceptionHandler,以便应用程序显示友好消息而不是崩溃。这是我尝试过的:

public partial class App : Application
{
    private void Application_Startup(object sender, StartupEventArgs e)
    {
        AppDomain.CurrentDomain.UnhandledException +=
            new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

        // The rest of the startup logic goes here
    }

    void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        Utilities.DisplayUnhandledException((Exception)e.ExceptionObject);
    }
}

但这不起作用。 CurrentDomain_UnhandledException 永远不会被调用。不幸的是,我无法更改应用程序的结构,这意味着我无法使用任务并行库。我不明白为什么这不起作用。有没有其他方法可以处理线程中抛出的异常?任何帮助表示赞赏。

【问题讨论】:

  • 试试Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);Application.ThreadException += Application_ThreadException;
  • 这里有一些详尽的解释:stackoverflow.com/questions/1472498/…

标签: c# wpf unhandled-exception


【解决方案1】:

你的方法是正确的。但是,您将无法阻止您的应用程序终止。

当您在应用程序中创建的线程上引发未处理的异常时,CurrentDomain_UnhandledException 将被调用,允许您记录或报告异常。但是,除非e.IsTerminatingfalse,否则您将无法阻止您的应用程序终止。您可以在 Exceptions in Managed Threads 中阅读有关此行为的更多信息。

如果您发现从未调用过CurrentDomain_UnhandledException,则应验证是否调用了Application_Startup 来设置处理程序。

如果您仍然遇到问题,您应该验证Utilities.DisplayUnhandledException 没有引发异常。这也将导致您的申请立即终止。特别是,如果e.ExceptionObject 不是Exception 类型,则将其转换为Exception 将引发异常。但是,正常情况下,当异常对象不是托管异常时,it will be wrapped in a RuntimeWrappedException

为避免您的应用程序终止,您需要在线程方法的“堆栈顶部”捕获异常。如果由于您无权访问代码而无法做到这一点,则未处理的异常表明软件存在错误,即使不方便,当发现软件错误时最好的做法是终止应用程序以避免损坏.

【讨论】:

    猜你喜欢
    • 2011-05-20
    • 2012-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多