0

I have a simple program but I am not sure why I didn't capture the AggregateException or just Exception in the caller? The following line of code: var webRequest = WebRequest.Create(url); will throw invalid url exception. But the exception is not captured in the caller code. Can anyone show me why I didn't capture the AggregateException in this case?

class Program
{
    static void GetWebResponseSizeAsync(string url)
    {
        var webRequest = WebRequest.Create(url);

        var webResponse = webRequest.GetResponse();

        using (var streamReader = new StreamReader(webResponse.GetResponseStream()))
        {
            string text = streamReader.ReadToEnd();

            Console.WriteLine("Read {0} bytes from web site {1}", text.Length, url);
        }
    }
    static void Main(string[] args)
    {
        string url = @"www.google.com";

        try
        {
            var task = Task.Run(()=>GetWebResponseSizeAsync(url));

            Console.WriteLine("....");
        }
        catch (AggregateException e)
        {
            Console.WriteLine("Catch exception: {0}", e.Message);
        }

        Console.WriteLine("Done");

        Console.ReadLine();
    }
}
iceheart
  • 33
  • 7
  • _"But the exception is not captured in the caller code"_ -- why should it? The exception is thrown in a different thread than the one that has the `try`/`catch`. Please explain more clearly why you think the code should do something different than what it's doing. (And as an aside, it makes no sense to name a method with the word `...Async` if that method does not do anything asynchronously.) – Peter Duniho Jul 05 '17 at 00:50
  • You seem to be confused about how exception handling with tasks work. The exception is thrown in the thread handling the task, not the thread where you placed the `try`/`catch`. If you want the exception to be observable in the original calling method, you need to wait for the task. Normally you'd do this with `await` (per marked duplicate), but in the `Main()` method you can't mark it `async`, so you'd have to just call `Wait()` on the `Task` object returned by `Task.Run()`, e.g. `task.Wait();`. – Peter Duniho Jul 05 '17 at 00:57
  • After all, without any sort of waiting, execution can exit the `try`/`catch` before the exception even gets a chance to be thrown. – Peter Duniho Jul 05 '17 at 00:58

0 Answers0