scarpacci
scarpacci

Reputation: 9194

C# - Task Exception not being caught

I am sure I am doinig something wrong, but when I try this example of the new threading task exception handling I keep getting the exception unhandled by user code. The whole point of the code is to show an example of how to catch errors in tasks.

Link: Task Exception Example

static void Main(string[] args)
        {
            var task1 = Task.Factory.StartNew(() =>
            {
                throw new MyCustomException("I'm bad, but not too bad!");
            });

            try
            {
                task1.Wait();
            }
            catch (AggregateException ae)
            {
                // Assume we know what's going on with this particular exception. 
                // Rethrow anything else. AggregateException.Handle provides 
                // another way to express this. See later example. 
                foreach (var e in ae.InnerExceptions)
                {
                    if (e is MyCustomException)
                    {
                        Console.WriteLine(e.Message);
                    }
                    else
                    {
                        throw;
                    }
                }

            }
        }

Most likely user error just not sure what (Using Visual Studio 2012);

Upvotes: 2

Views: 2184

Answers (1)

mayhewr
mayhewr

Reputation: 4021

From the page you cited:

Note

When "Just My Code" is enabled, Visual Studio in some cases will break on the line that throws the exception and display an error message that says "exception not handled by user code." This error is benign. You can press F5 to continue and see the exception-handling behavior that is demonstrated in these examples. To prevent Visual Studio from breaking on the first error, just uncheck the "Just My Code" checkbox under Tools, Options, Debugging, General.

Upvotes: 15

Related Questions