sm.abdullah
sm.abdullah

Reputation: 1802

How to handle exception occured inside object event from outside?

i have a piece of code like this.

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)
        {

        }

here you can see the web browser event it can raise an Exception i want to handle this exception like this.

 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);
            }
        }
    }

can you please help me out ? it is not working because of event.

Upvotes: 1

Views: 220

Answers (1)

Tim Rogers
Tim Rogers

Reputation: 21713

The DocumentCompleted event fires in a different thread to the main application. You can see this if you open the Threads window of Visual Studio while you are debugging. You cannot throw an exception from one thread to another.

You don't say if you are using WPF, or Windows Forms, but assuming the latter, you should use the Invoke method on your form or control to update the UI or open a message box, rather than trying to throw an exception.

Upvotes: 1

Related Questions