3

我尝试使用

http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx#Y399

但是当我这样做时

throw new ArgumentNullException("playlist is empty");

我什么都得不到。我敢打赌我错过了一些非常明显的东西。

这是我的代码。

using System;
using System.Security.Permissions;
using System.Windows.Forms;
using System.Threading;

namespace MediaPlayer.NET
{
    internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
        private static void Main()
        {
            // Add the event handler for handling UI thread exceptions to the event.
            Application.ThreadException += new ThreadExceptionEventHandler(UIThreadException);

            // 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 non-UI thread exceptions to the event. 
            AppDomain.CurrentDomain.UnhandledException +=
                new UnhandledExceptionEventHandler(UnhandledException);

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

        private static void UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            MessageBox.Show("UnhandledException!!!!");
        }

        private static void UIThreadException(object sender, ThreadExceptionEventArgs t)
        {
            MessageBox.Show("UIThreadException!!!!",
                            "UIThreadException!!!!", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
            Application.Exit();
        }
    }
}
4

2 回答 2

10

您的代码运行良好,我想不出很多可能的故障模式。除了一个问题,当您在 Windows 8 之前的 64 位操作系统上调试 32 位代码时,调试器和 Windows SEH 之间的交互存在问题。这可能会导致异常在窗体中发生时被吞下而没有任何诊断。加载事件或 OnLoad() 方法覆盖。检查链接的帖子以了解解决方法,最简单的一个是项目 + 属性,构建选项卡,平台目标 = AnyCPU,如果你看到它,请取消勾选“首选 32 位”。

通常,您通过不让 Application.ThreadException 的默认异常处理显示对话框来做适当的事情。但保持简单,像这样:

#if (!DEBUG)
      Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
#endif

现在您再也不必担心 ThreadException,所有异常都会触发 AppDomain.UnhandledException 事件处理程序。并且代码周围的#if 仍然允许您调试未处理的异常,当引发异常时调试器将自动停止。

将此添加到 UnhandledException 方法以防止出现 Windows 崩溃通知:

        Environment.Exit(1);
于 2011-02-01T16:41:16.187 回答
2

你还没有显示你在哪里扔ArgumentNullException. 我的猜测是它要么在构造函数中MediaPlayerForm(这意味着它在消息循环开始之前),要么在不同的线程中。Application.ThreadException仅处理在运行消息循环的 Windows 窗体线程上捕获的异常。

于 2011-02-01T16:03:12.593 回答