我尝试使用
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();
}
}
}
您的代码工作正常,我能想到的可能的故障模式并不多。除了一个,有问题当您在 Windows 8 之前的 64 位操作系统上调试 32 位代码时,调试器与 Windows SEH 之间的交互中。当异常发生在窗体的 Load 事件或 OnLoad() 中时,这可能会导致异常被吞没而没有任何诊断方法重写。检查链接的帖子以获取解决方法,最简单的一种是项目 + 属性,构建选项卡,平台目标 = AnyCPU,如果看到它,请取消选中“首选 32 位”。
通常,您通过不让 Application.ThreadException 的默认异常处理显示对话框来执行适当的操作。但保持简单,这样做:
#if (!DEBUG)
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
#endif
现在您不必再担心 ThreadException,所有异常都会触发 AppDomain.UnhandledException 事件处理程序。并且代码周围的 #if 仍然允许您调试未处理的异常,当引发异常时调试器将自动停止。
将其添加到 UnhandledException 方法中以防止显示 Windows 崩溃通知:
Environment.Exit(1);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)