如何在控制台应用程序中捕获未处理的异常

How to catching Unhandled Exceptions in Console 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
}