WebClient.DownloadDataAsync本身真的会抛出异常吗

本文关键字:抛出异常 真的 DownloadDataAsync WebClient | 更新日期: 2023-09-27 18:00:29

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

例外情况:

  • ArgumentNullException-地址参数为null
  • WebException-由BaseAddress和address组合而成的URI无效-或-下载资源时出错

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

换句话说,WebClient.DownloadDataAsync周围的try/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块没有被命中(而e.Errors代码是),但我不知道下载调用本身是否会引发其他情况。

WebClient.DownloadDataAsync本身真的会抛出异常吗

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