0

I wont get the the aggregate exception is not getting executed

namespace ExceptionTest { class Program { static void Main(string[] args) { Task<int> t1 = new Task<int>(() => Add()); try { t1.Start(); } catch (AggregateException ag) { Console.WriteLine(ag.Message); } Console.ReadLine(); } static int Add() { try { throw new ArgumentException("Exception"); } catch(Exception e) { throw e; } } } } 

1 Answer 1

2

Start() will never throw in a situation like this. It only starts the Task, and immediately returns; it doesn't wait until the Task completes.

If you want to catch the exception, you should use Wait():

Task<int> t1 = Task.Factory.StartNew(() => Add()); try { t1.Wait(); } catch (AggregateException ag) { Console.WriteLine(ag.Message); } 

And if you use Wait(), you can use Task.Factory.StartNew() (or Task.Run() on .Net 4.5) instead of constructor with Start(). And you also don't need Console.ReadLine() anymore. (Both changes reflected in the above code.)

Sign up to request clarification or add additional context in comments.

1 Comment

Also calling to Task Result will re-throw exception if it thrown earlier in Task execution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.