简体   繁体   中英

Exception thrown in async method is not caught - why?

I have a hard time understanding how async/await works in various non-happy-path cases. For example, I have the following code:

    class Program
    {
        static void Main(string[] args)
        {
            Do();
            Console.ReadLine();
        }

        private static void Do()
        {
            TaskScheduler.UnobservedTaskException += (s, e) =>
            {
                Console.WriteLine($"Unobserved Exception : {e.Exception.Message}");
                e.SetObserved();
            };
            
            try
            {                
                ThrowsAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Caught in try/catch  : {ex.Message}");
            }
        }

        private static async Task ThrowsAsync()
        {    
            Console.WriteLine("Throwing");
            throw new Exception("FAILURE");
        }
    }

There are two things that I do not understand:

  1. The ThrowsAsync method is async, however, it does not contain any await . I would assume that in such a case the method would execute like a "normal" synchronous method. However, the exception that it throws is never caught in the catch block.
  2. Trying to somehow catch the exception, I added the handler for TaskScheduler.UnobservedTaskException . However, it is never executed. Why is that?

I know that the exception would be caught if I awaited ThrowsAsync . However, I'm experimenting to get a better understanding of how it works.

I'm running that code using .NET 5 and Linux-based OS.

  1. As described for example in this blog post by Stephen Cleary - the state machine for async methods will capture exceptions from your code and place them on the returned task, ie method invocation will not throw, you will be able to catch exception if await the result.

  2. As for TaskScheduler.UnobservedTaskException - check out this answer and be sure to run code in Release mode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM