如何处理来自外部的对象事件内部发生的异常
本文关键字:事件 对象 内部 异常 外部 何处理 处理 | 更新日期: 2023-09-27 18:34:40
我有一段这样的代码。
class Facebook
{
WebBrowser wb = new WebBrowser();
public bool isDone = false;
public Facebook()
{
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
}
public void Navidate(string URL = "http://www.facebook.com")
{
wb.Navigate(URL);
}
public void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wb = sender as WebBrowser;
if (wb != null && wb.StatusText.Contains("404"))
{
// i want to throw this exception to outside how ?
throw new ServerNotFound("Error 404");
}
else
{
isDone = true;
}
}
}
public class ServerNotFound : Exception
{
public ServerNotFound(string Message)
: base(Message)
{
}
在这里你可以看到它可以引发异常的 Web 浏览器事件我想像这样处理这个异常。
static class Program
{
[STAThread]
static void Main()
{
try
{
Facebook fb = new Facebook();
fb.Navidate();
do
{
Application.DoEvents();
}
while (!fb.isDone);
}
catch (ServerNotFound ex)
{
// i want to handle that exception here ?
MessageBox.Show(ex.Message);
}
}
}
你能帮帮我吗? 由于事件,它不起作用。
DocumentCompleted
事件在与主应用程序不同的线程中触发。如果在调试时打开 Visual Studio 的"线程"窗口,则可以看到这一点。不能将异常从一个线程抛到另一个线程。
没有说您使用的是 WPF 还是 Windows 窗体,但假设是后者,您应该在窗体或控件上使用 Invoke 方法来更新 UI 或打开消息框,而不是尝试引发异常。