% -*- latex -*-

\chapter{Worklet Error Handling}
\label{chap:WorkletErrorHandling}

\index{worklet|(}
\index{worklet!creating|(}

\index{errors|(}

\index{errors!execution environment|(}
\index{errors!worklet|(}
\index{worklet!error handling|(}

It is sometimes the case during the execution of an algorithm that an error condition can occur that causes the computation to become invalid.
At such a time, it is important to raise an error to alert the calling code of the problem.
Since \VTKm uses an exception mechanism to raise errors, we want an error in the execution environment to throw an exception.

However, throwing exceptions in a parallel algorithm is problematic.
Some accelerator architectures, like CUDA, do not even support throwing exceptions.
Even on architectures that do support exceptions, throwing them in a thread block can cause problems.
An exception raised in one thread may or may not be thrown in another, which increases the potential for deadlocks, and it is unclear how uncaught exceptions progress through thread blocks.

\VTKm handles this problem by using a flag and check mechanism.
When a worklet (or other subclass of \vtkmexec{FunctorBase}) encounters an error, it can call its \classmember*{FunctorBase}{RaiseError} method to flag the problem and record a message for the error.
Once all the threads terminate, the scheduler checks for the error, and if one exists it throws a \vtkmcont{ErrorExecution} exception in the control environment.
Thus, calling \classmember*{FunctorBase}{RaiseError} looks like an exception was thrown from the perspective of the control environment code that invoked it.

\vtkmlisting{Raising an error in the execution environment.}{ExecutionErrors.cxx}

\index{worklet!error handling|)}
\index{errors!worklet|)}
\index{errors!execution environment|)}

\index{errors!assert|(}
\index{assert|(}

It is also worth noting that the \vtkmmacro{VTKM\_ASSERT} macro described in Section~\ref{sec:Assert} also works within worklets and other code running in the execution environment.
Of course, a failed assert will terminate execution rather than just raise an error so is best for checking invalid conditions for debugging purposes.

\index{assert|)}
\index{errors!assert|)}

\index{errors|)}

\index{worklet!creating|)}
\index{worklet|)}
