【问题标题】:C# Winforms handle unhandled exceptionsC# Winforms 处理未处理的异常
【发布时间】:2019-05-26 12:15:49
【问题描述】:

我想在我的应用程序中捕获所有未处理的异常。所以我用这段代码来捕获所有未处理的异常:

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);
    }
}

我试图用 0 分来引发这些异常:

在主线程上完美运行:

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; 行,所以我有一个异常循环。知道可能是什么问题吗?线程只被调用一次。

【问题讨论】:

  • 你怎么称呼thread.Start(),我的意思是在哪里?
  • Application.Exit() 不是终止应用程序的正确方法,它只会让车轮运转。当汽车撞到墙上时,你已经没有轮子了。请改用 Environment.Exit()。
  • @AliBahrami 我在按钮点击事件中使用它
  • @HansPassant 不是因为这个,我已经删除了,还是有这个问题。
  • 当您可以向我们展示时,推测“我已经删除它”可能意味着什么并不是很有用。指导是替换它。

标签: c# multithreading winforms exception


【解决方案1】:

您需要更改应用程序UnhandledExceptionModeUnhandledExceptionMode.CatchException 使事情正常工作。微软已经写了一篇非常好的文章here

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

    [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 捕获异常,显示消息并关闭应用程序

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-01
  • 1970-01-01
  • 2011-11-19
  • 2011-12-28
  • 2011-01-29
相关资源
最近更新 更多