Error catching with webexception

Nathan picture Nathan · Nov 3, 2011 · Viewed 14.7k times · Source

I'm using a simple webclient to retrieve some XML from a web service, I have this encased in a simple try, catch block (catching WebException). Like the following;

try
        {
            WebClient client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri("http://ip/services"));
        }
        catch (WebException e)
        {

            Debug.WriteLine(e.Message);
        }

No if i change the IP address to one that isn't valid, i would of expected it to throw an exception and output the message to the debug window. But it doesn't, it seems the catch block isn't even getting executed. Nothing appears and the debug windows apart from the following;

A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
A first chance exception of type 'System.Net.WebException' occurred in System.Windows.dll
A first chance exception of type 'System.Net.WebException' occurred in System.Windows.dll

My code looks right to me so I can't understand why exceptions are not being caught?

Answer

fluent picture fluent · Nov 3, 2011

From your description of the error messages I would assume that the actual exception thrown is of type "FileNotFoundException".

Have you tried just catching the exception and checking the type? It may be that the web exception is an inner exception.

        try
        {
            WebClient client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri("http://ip/services"));
        }
        catch (Exception ex)
        {

            Debug.WriteLine(ex.GetType().FullName);
            Debug.WriteLine(ex.GetBaseException().ToString());
        }

UPDATE : I just noticed that what you are actually calling is an async method.

As a sanity check I would suggest swapping to the non async method and checking the error produced by that.

WebClient.DownloadString Method (Uri)

You may also benefit from looking at this page which walks through catching async errors using the web client as an example.

Async Exceptions