Why exceptions thrown within a task are silent exception and you never know if a certain exception has been thrown
try
{
Task task = new Task(
() => {
throw null;
}
);
task.Start();
}
catch
{
Console.WriteLine("Exception");
}
the program run successfully in a complete silence!
where the behavior of threads is different
try
{
Thread thread = new Thread(
() => {
throw null;
}
);
thread .Start();
}
catch
{
Console.WriteLine("Exception");
}
a null pointer exception will be thrown in this case.
What is the difference?
The behaviour of that scenario depends on what framework you have; in 4.0, you actually need to be careful – if you don’t handle
TaskScheduler.UnobservedTaskException, it will error later when it gets collected/finalized, and will kill your process.This changes in 4.5, IIRC.
To check the outcome of a
Taskthat might fail, you could register a continuation – i.e. callContinueWithand check the result’s exception. Alternatively, accessing the.Resultof the task (which would also do an implicitWait()) will re-surface the exception that happened. It is good to observe the result of a task, as that clears the finalization flag, meaning it can be collected more cheaply.