Reputation: 35
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; }
}
}
}
Upvotes: 0
Views: 81
Reputation: 244757
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.)
Upvotes: 2