将未处理的异常记录到日志文件中

Bha*_*tel 5 vb.net logging exception-handling exception winforms

如何将未处理的异常记录到 WinForms 应用程序的日志文件中,以便轻松确定异常的来源?

stu*_*rtd 4

首先,您需要捕获未处理的异常。将此代码的 VB.Net 版本添加到您的主程序中:

Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += ApplicationThreadException;
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
Run Code Online (Sandbox Code Playgroud)

然后添加事件处理程序:

static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
{
    Exception ex = e.ExceptionObject as Exception;
    if (ex != null)
    {
       Console.WriteLine("Unhandled exception: {0}", e.Exception);      
    }
}

static void ApplicationThreadException(object sender, ThreadExceptionEventArgs e)
{
    Console.WriteLine("Unhandled application exception: {0}", e.Exception);
}
Run Code Online (Sandbox Code Playgroud)

然后您可以使用您选择的日志方法记录错误。(抱歉 C# 代码!)

  • 如果您使用 try/catch,只需将日志记录代码添加到 catch 块 - 这是为了拾取 **未处理的** 异常,即那些未在 try/catch 块中捕获的异常。 (2认同)