0

Hello I want to catch a Exception of a async method but it did not work look a this example :

        public void TryToCatchException()
        {
            try
            {
                _ =LongRunningMethod();
            }
            catch (MyException)
            {
                Console.WriteLine("catched");
            }
        }


        public static async Task LongRunningMethod()
        {
            await Task.Run(() =>
            {
                try
                {
                    Task.Delay(1000); //simulation of work
                    throw new ArgumentException(); // this is a example
                }
                catch (ArgumentException)
                {
                    throw new MyException;
                }

            });
        }

if I launch the debugger will say that the exception "MyException" is NOT catched... can someone help me ?

5
  • Why are you using Task.Run? Commented Apr 10, 2021 at 15:32
  • @JHBonarius because I use a API Method that block the current thread for 10 to 15 seconds and I don't want that. Commented Apr 10, 2021 at 15:33
  • Do not mix Task and threads Commented Apr 10, 2021 at 15:46
  • 2
    As you don't await LongRunningMethod, TryToCatchException will return (almost) immediately and cannot catch any exceptions. Commented Apr 10, 2021 at 15:58
  • @KlausGütter Thanks you for your response :) Commented Apr 10, 2021 at 16:08

1 Answer 1

3

When you discard tasks, those exceptions are not observed:

_ =LongRunningMethod();

If you want to catch exceptions from LongRunningMethod, then you need to await the task returned from that method:

await LongRunningMethod();
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks you for your comment, but my debugger still say that the exception is "Exception User-Unhandled". ^^ That is normal ?
Yes, when you run it in the debugger.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.