Exceptions in tasks
Handling exceptions in tasks is a tricky business. The best approach is to handle exceptions explicitly by wrapping the task code in a try..except block.
The following code shows how exceptions are handled in the ExplicitExceptionTask task. This task is executed when the user clicks on the Exception 1 button in the ParallelTasks demo.
The code always raises an exception, so LongTaskCompleted is never called. Instead of that, the code always executes the except block, which queues LongTaskError to be executed in the main thread.
As the queued code is not executed immediately, we have to grab the exception object by calling the AcquireExceptionObject method. Variable capturing will take care of the rest. If we did not call ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access