我试过用
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();
}
}
}
最佳答案
您的代码运行良好,我能想到的可能的故障模式不多。除了一个,there's a problem当您在 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);
关于c# - 如何使用线程异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4864835/