首页 > 解决方案 > 如何在控制台应用程序中捕获未处理的异常

问题描述

我经常在我的控制台应用程序中发现未处理的异常。然后它会挂起并停止所有进程。在程序正常工作之前,我还被迫重新启动程序。

未处理的异常:

我的程序是一个服务器程序。我不希望它停止工作,因为它会影响业务。

我该如何处理这个错误?

标签: c#exception-handlingconsole-application

解决方案


在 main 方法中注册一个全局异常处理程序,如下所示:

//Add handler to handle the exception raised by additional threads
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

然后处理方法中所有未处理的异常CurrentDomain_UnhandledException

private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    //Your logic here, for ex., log the exception somewhere
}

推荐阅读