好吧,基于另一个我问过我的程序没有运行的问题,我正在尝试将此代码放入我的程序中,希望能指出任何未处理的例外情况。但是,它不像我写的那样工作。
private void FileSort_Load(object sender, EventArgs e)
{
this.Size = new System.Drawing.Size(693, 603);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Main_FormClosing);
System.AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
//insert here anything that will occur on the program's start
}
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
throw new NotImplementedException();
// MessageBox.Show(e.ExceptionObject); //why doesn't this work?!?!?!?!?!?!?!?
}
所以我的问题显然是上面代码中的Messagebox.Show()
函数。它告诉我它无法从object
转换为string
。我尝试使用ToString()
函数,但这会导致更多问题。为什么这不会按照它的方式工作? (我收到这个建议作为我的另一个问题的答案,但我对此并不太熟悉(因为我是C#的新手,以及整个OOP)所以我不确定我做错了什么,我只需在输入System.AppDomain.CurrentDomain.UnhandledException +=
)
任何帮助都将不胜感激。
答案 0 :(得分:4)
不会达到那个声明,因为它上方有一个抛出。如果你把:
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show(e.ExceptionObject.ToString());
throw new NotImplementedException();
}
它可能会做你想要的。您需要ToString
,因为Show
不会将对象作为唯一参数。你说这引起了“更多的问题”,但这真的太模糊了,无法提供帮助。
答案 1 :(得分:0)
(假设您将对异常进行注释,并取消对相关行的注释,通常您无法将对象传递给需要字符串的方法,因此您需要将所需的字符串传递给Show方法。
然后问题是你想要它显示什么字符串?所有异常都有Message属性。这可能是您要显示的字符串,因此请将代码更改为
MessageBox.Show((Exception)(e.ExceptionObject).Message)
这样做你想要的吗?如果没有,你能准确解释你想要它做什么吗?
答案 2 :(得分:0)
MessageBox.Show()
采用字符串,而e.ExceptionObject
是documentation的对象。
你可以试试这个:
MessageBox.Show(e.ExceptionObject.ToString());
答案 3 :(得分:0)
您应该写入Windows事件日志,而不是尝试显示消息框。然后,只需记录流程的每一步,确定问题所在。
这link might会给你一些帮助。