gpt4 book ai didi

c# - WebClient.DownloadDataAsync 真的会抛出异常吗?

转载 作者:行者123 更新时间:2023-11-30 17:55:33 24 4
gpt4 key购买 nike

MSDN documentation for WebClient.DownloadDataAsync列出了调用该方法可能产生的两个潜在异常。

异常(exception)情况:

  • ArgumentNullException - 地址参数为空。
  • WebException - 通过组合 BaseAddress 和地址形成的 URI 无效。 - 或 - 下载资源时出错。

虽然我不怀疑这些异常可能会在调用此代码时的某个时刻发生,但它们是否真的源自那条执行线,还是只会出现在引发的 DownloadDataCompleted 事件的 e.Error 属性?

换句话说,围绕 WebClient.DownloadDataAsynctry/catch 是否真的捕获了任何东西,或者它们只是描述了可能显示的错误在 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.");
}
}

我尝试了一个简单的 404 错误,但没有命中 catch block (而 e.Errors 代码命中),但我不知道下载调用是否会引发其他情况本身。

最佳答案

是的,DownloadDataAsync 会直接抛出 ArgumentNullException。它还会抛出 NotSupportedExceptionUriFormatException。但是任何 WebException 都将通过回调(即事件)出现。

关于c# - WebClient.DownloadDataAsync 真的会抛出异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14990801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com