Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does WebClient.DownloadDataAsync really throw exceptions itself?

Tags:

c#

webclient

The MSDN documentation for WebClient.DownloadDataAsync lists two potential exceptions that may come from calling that method.

Exceptions:

  • ArgumentNullException - The address parameter is null.
  • WebException - The URI formed by combining BaseAddress and address is invalid. -or- An error occurred while downloading the resource.

While I don't doubt that those exceptions may occur at some point when this code is called, can they actually originate from that line of execution or will they only surface in the raised DownloadDataCompleted event's e.Error property?

In other words, would a try/catch around WebClient.DownloadDataAsync actually catch anything or are they just describing the errors that could show up in e.Error?

using (WebClient webClient = new WebClient()) {
    webClient.DownloadDataCompleted += (sender, e) => {
        if (e.Error != null) {
            // Exceptions definitely available here.
            Console.WriteLine(e.Error.Message);
        }
        else {
            Console.WriteLine("Success!");
        }
    };
    try {
        webClient.DownloadDataAsync(someUri);
    }
    catch {
        // Would this ever be hit?
        Console.WriteLine("Caught an exception from DownloadDataAsync.");
    }
}

I tried a simple 404 error and the catch block wasn't hit (while the e.Errors code was), but I didn't know if some other situation would throw from the download call itself.

like image 619
patridge Avatar asked May 17 '26 01:05

patridge


1 Answers

Yes, DownloadDataAsync will throw ArgumentNullException directly. It will also throw NotSupportedException and UriFormatException. But any WebExceptions will come through the callback (i.e. the event).

like image 190
Peter Ritchie Avatar answered May 18 '26 14:05

Peter Ritchie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!