When handling exceptions in TPL tasks, I came across two ways to handle exceptions. The first throws an exception inside the task and returns it as a result as follows:
var task = Task<Exception>.Factory.StartNew(
() =>
{
try
{
return null;
}
catch (System.Exception e)
{
return e;
}
});
task.ContinueWith(
r =>
{
if (r.Result != null)
{
}
});
The second is the one shown in the documentation, and I think the right way to do something is:
var task = Task.Factory.StartNew(
() =>
{
});
task.ContinueWith(
r =>
{
if (r.Exception != null)
{
r.Exception.Handle(y => true);
}
});
I am wondering if something is wrong with the first approach? I got “unhandled aggregated exceptions” exceptions every time using this technique, and wondered how this could happen.
To clarify, I think the second template is better, but I have a piece of code that uses the first template, and I'm trying to figure out if it needs refactoring, i.e. if it turns out that not all exceptions will be caught.