我正在写一个小库,捕获所有未处理的异常,并显示一个小对话框(类似于NF的常用对话框),这使用户有机会将异常发送给开发人员。为此,我像这样使用AppDomain的UnhandledException-Event:
app.UnhandledException += (object sender, UnhandledExceptionEventArgs e) =>
{
ExceptionHandler handler = new ExceptionHandler((Exception)e.ExceptionObject, ExEntry);
UnhandledExceptionListened(handler);
if (Properties.Settings.Default.ShowStandardExceptionDialog)
{
ExceptionDialog exdialog = new ExceptionDialog(handler);
exdialog.ShowDialog();
}
};
ExceptionHandler和ExEntry是我的图书馆的类。但是:如果发生异常,编译器将跳入我的Lambda-Expression,尝试调试第一行代码,然后显示之前发生的错误,而无需解决其余的Lambda。
但是,如果我只写:
app.UnhandledException += (object sender, UnhandledExceptionEventArgs e) =>
{
ExceptionDialog exdialog = new ExceptionDialog(handler);
exdialog.ShowDialog();
};
它完美地工作。有谁知道为什么这不起作用?
最佳答案
可能有两个原因。
一种是您没有正确设置UnhandledExceptionMode:
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
另一个是您没有处理ThreadException,并且抛出的异常不是未处理的异常,而是线程异常。
以下是一个示例,您需要根据自己的情况对其进行修改:
Application.ThreadException+=
new ThreadExceptionEventHandler(Log.WriteThreadException);
AppDomain.CurrentDomain.UnhandledException+=
new UnhandledExceptionEventHandler(Log.WriteUnhandledException);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
关于c# - UnhandledException事件不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16717884/