繁体   English   中英

C#Winforms处理未处理的异常

[英]C# Winforms handle unhandled exceptions

我想在我的应用程序中捕获所有未处理的异常。 因此,我使用以下代码捕获了所有未处理的异常:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
    {
        SaveEx(e.Exception);
        Application.Exit();
    }

    static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        SaveEx((Exception)e.ExceptionObject);
        Application.Exit();
    }

    static void SaveEx(Exception ex)
    {
        bool exists = System.IO.Directory.Exists(Path.GetDirectoryName(@"C:\AppLogs\"));

        if (!exists)
            System.IO.Directory.CreateDirectory(Path.GetDirectoryName(@"C:\AppLogs\"));


        String filePath = @"C:\AppLogs\" + DateTime.Now.ToString("yyyy-dd-M--HH-mm-ss") + ".txt";

        String log = "===========Start=============\r\n";

        log += "Error Message: " + ex.Message + "\r\n";
        log += "Stack Trace: " + ex.StackTrace + "\r\n";

        log += "===========End=============";

        System.IO.File.WriteAllText(filePath, log);
    }
}

我试图用零除引发这些异常:

在主线程上,它的工作完美:

int t = 0;
int r = 5 / t;

但是当我尝试在Thread执行此操作时:

 Thread thread = new Thread(delegate()
 {
      int t = 0;
      int r = 5 / t;
 });
 thread.Start();

调用了CurrentDomain_UnhandledException函数,但它一直在调用int r = 5 / t; 在我的代码中排成一行,所以我有一个异常循环。 知道可能是什么问题吗? 该线程仅被调用一次。

您需要将Application UnhandledExceptionMode更改为UnhandledExceptionMode.CatchException才能正常工作。 微软已经在这里写了一篇很好的文章。

我试图模拟您的工作。 一切正常,请看我的例子。

    [STAThread]
    static void Main()
    {
        // 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 UI thread exceptions to the event.
        Application.ThreadException += Application_ThreadException;

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

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }

    private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
    {
        MessageBox.Show(e.Exception.Message, "Application_ThreadException");
        Application.Exit();
    }

    private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
        var exception = e.ExceptionObject as Exception;
        MessageBox.Show(exception.Message, "CurrentDomain_UnhandledException");
        Application.Exit();
    }

因此,如果我们在如下所示的线程内引发异常:

    private void button1_Click(object sender, EventArgs e)
    {
        var thread = new Thread(delegate () {
            throw new DivideByZeroException();
        });

        thread.Start();
    }
  1. button1_Click被触发。
  2. 线程开始,并引发DividedByZeroException
  3. CurrentDomain_UnhandledException捕获异常,显示消息并关闭应用程序

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM