The MSDN documentation for WebClient.DownloadDataAsync lists two potential exceptions that may come from calling that method.
Exceptions:
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With