Cookbook » Exception Handling

This chapter discusses how to handle exceptions in Taskflow, so you can correctly catch or propagate exceptions within your workloads.

Understand the Logic of Exception Handling in Taskflow

Exception handling is a powerful feature in Taskflow that distinguishes it from other task-parallel libraries that ignore this aspect. Taskflow follows a simple yet robust design to handle exceptions in a multi-threaded environment, ensuring program correctness without sacrificing parallel efficiency. The logic can be understood through three different scenarios, depending on how a task is executed and how the runtime reports errors.

TaskflowExceptionHandling ExceptionHandling Exception Handling in Taskflow Scenarios A task throws an exception ExceptionHandling->Scenarios Immediate Scenario 1: Synchronous Exception Propagation Scenarios->Immediate Propagation Scenario 2: Asynchronous Exception Propagation Scenarios->Propagation Silent Scenario 3: Silent Exception Propagation Scenarios->Silent

When multiple scenarios are applicable, Taskflow resolves exceptions by prioritizing scenario 1, then scenario 2, and finally scenario 3. We start with a brief overview of the three scenarios and then examine different use cases in more detail.

Scenario 1: Synchronous Exception Propagation

If the taskflow is executed in a blocking context where the application thread waits for completion, such as tf::Executor::corun, exceptions are immediately propagated to the caller. In this scenario, the executor does not defer or aggregate errors; instead, it synchronously rethrows the exception to the application thread as soon as it is detected.

try {
  executor.corun(taskflow); 
}
catch(const std::exception& e) {
  std::cerr << e.what();
}

Scenario 2: Asynchronous Exception Propagation

When you launch tasks using functions like tf::Executor::run or tf::Executor::async, any exception thrown within the task is captured and stored in a shared state associated with the returned tf::Future or std::future. This exception can later be rethrown when you access the result of the shared state.

tf::Future<void> fu = executor.run(taskflow);
try {
  fu.get(); 
}
catch(const std::exception& e) {
  std::cerr << e.what();
}

Scenario 3: Contextual Exception Propagation

Unlike scenarios 1 and 2, where exceptions are immediately reported to a waiting thread or an observable shared state, this scenario is reached only when no such reporting context exists. In such cases, the exception is not reported to the caller by default. Instead, the runtime first attempts to propagate the exception to the nearest parent execution context, if one exists. If no such parent context exists, the exception is silently suppressed.

// A silent-async task with no parent context: 
// the exception is silently suppressed.
executor.silent_async([&](){ 
  throw std::runtime_error("exception is silently caught by this task");
});

// A silent-async task with a parent context:
// the exception is propagated to the parent task group.
executor.silent_async([&](){ 
  tf::TaskGroup tg = executor.task_group();
  tg.silent_async([](){ 
    throw std::runtime_error("exception is propagated to the parent task group");
  });
  try {
    tg.corun();
  }
  catch(std::runtime_error& e) {
    std::cerr << e.what(); 
  }
});

Algorithm Flow of Exception Handling

The figure below illustrates how Taskflow processes exceptions and prioritizes their handling according to the availability of an execution context. When a task throws an exception, the runtime first walks up the task hierarchy to mark the execution path as exceptional and identify two types of anchor nodes, explicit anchor and implicit anchor (i.e., candidate nodes that will catch the exception). If an explicit anchor is found, indicating a blocking execution context like corun or join, the exception is immediately captured and later rethrown on the waiting application thread (Scenario 1). If no explicit anchor exists, the runtime next checks for an associated shared state, allowing the exception to be reported asynchronously later when the shared state is accessed (Scenario 2). Failing that, the exception is propagated to the nearest implicit anchor, such as a parent task group, if one exists (Scenario 3).Only when none of these reporting contexts are available does the runtime suppress the exception by storing it locally in the throwing task. This algorithm ensures exceptions are reported whenever possible while preserving safe and efficient parallel execution.

ProcessException start Exception thrown by task mark Traverse to the root to find exception catcher (explicit & implicit anchors) start->mark explicit Explicit anchor found? (blocking context) mark->explicit explicit_catch Store exception in explicit anchor (first exception wins) → Scenario 1 explicit->explicit_catch yes topology Shared state found? (e.g., promise, topology) explicit->topology no topology_catch Store exception in the shared state (first exception wins) → Scenario 2 topology->topology_catch yes implicit Implicit anchor found? (e.g., task group, runtime task) topology->implicit no implicit_catch Store exception in implicit anchor (first exception wins) → Scenario 3 implicit->implicit_catch yes silent Store exception locally (no exception report) implicit->silent no

Example: Catch an Exception from a Running Taskflow

When a task throws an exception, the executor captures it and stores it in the shared state associated with the returned tf::Future (a derived class of std::future). You can later catch the exception by calling the get method:

tf::Executor executor;
tf::Taskflow taskflow;
taskflow.emplace([](){ throw std::runtime_error("exception"); });
try {
  executor.run(taskflow).get();
}
catch(const std::runtime_error& e) {
  std::cerr << e.what() << std::endl;
}

When a task throws an exception, the executor automatically cancels the execution of its parent taskflow. All subsequent tasks that depend on the exception-throwing task will be skipped. For example, consider a taskflow with two tasks, A and B, where B runs after A. If A throws an exception, the executor cancels the remaining execution of the taskflow, preventing any dependent tasks (including B) from running.

tf::Executor executor;
tf::Taskflow taskflow;
tf::Task A = taskflow.emplace([](){ throw std::runtime_error("exception on A"); });
tf::Task B = taskflow.emplace([](){ std::cout << "Task B\n"; });
A.precede(B);
try {
  executor.run(taskflow).get();
}
catch(const std::runtime_error& e) {
  std::cerr << e.what() << std::endl;
}
~$ exception on A
# execution of taskflow is cancelled after an execution is thrown

When multiple tasks throw exceptions simultaneously, the executor will store only one of these exceptions in the shared state. Other exceptions will still be caught locally by their throwing tasks, but their handling will ignored. For example, in the following taskflow, both task B and task C may throw exceptions concurrently. Only one exception, either from task B or task C, will be propagated.

tf::Executor executor;
tf::Taskflow taskflow;

auto [A, B, C, D] = taskflow.emplace(
  []() { std::cout << "TaskA\n"; },
  []() { 
    std::cout << "TaskB\n";
    throw std::runtime_error("Exception on Task B");
  },
  []() { 
    std::cout << "TaskC\n"; 
    throw std::runtime_error("Exception on Task C");
  },
  []() { std::cout << "TaskD will not be printed due to exception\n"; }
);

A.precede(B, C);  // A runs before B and C
D.succeed(B, C);  // D runs after  B and C

try {
  executor.run(taskflow).get();
}
catch(const std::runtime_error& e) {
  std::cerr << e.what();  // exception of either B or C is caught
}

Example: Catch an Exception from a Subflow

When you join a subflow using tf::Subflow::join, you can catch an exception thrown by its children tasks. For example, the following code catches an exception from the child task A of the subflow sf:

tf::Executor executor;
tf::Taskflow taskflow;

taskflow.emplace([](tf::Subflow& sf) {
  tf::Task A = sf.emplace([]() { 
    std::cout << "Task A\n";
    throw std::runtime_error("exception on A"); 
  });
  tf::Task B = sf.emplace([]() { 
    std::cout << "Task B\n"; 
  });
  A.precede(B);
  
  // catch the exception
  try {
    sf.join();
  }
  catch(const std::runtime_error& e) {
    std::cerr << "exception thrown during subflow joining: " << e.what();
  }
});

executor.run(taskflow).get();

When an exception is thrown, it will cancel the execution of the parent subflow. All the subsequent tasks that depend on that exception task will not run. The above code example has the following output:

Task A
exception thrown during subflow joining: exception on A

Uncaught exception will be propagated to the parent level until being explicitly caught. For example, the code below will propagate the exception to the parent of the subflow, which in this case in its taskflow.

tf::Executor executor;
tf::Taskflow taskflow;

taskflow.emplace([](tf::Subflow& sf) {
  tf::Task A = sf.emplace([]() {
    std::cout << "Task A\n";
    throw std::runtime_error("exception on A");
  });
  tf::Task B = sf.emplace([]() {
    std::cout << "Task B\n"; 
  }); 
  A.precede(B);

  // uncaught exception will propagate to the parent
  sf.join();
});

try
{
  executor.run(taskflow).get();
}
catch (const std::runtime_error& e)
{
  std::cerr << "exception thrown from running the taskflow: " << e.what();
}
Task A
exception thrown from running the taskflow: exception on A

Example: Catch an Exception from an Async Task

Similar to std::future, tf::Executor::async stores any exception in the shared state referenced by the returned std::future handle.

tf::Executor executor;
auto fu = executor.async([](){ throw std::runtime_error("exception"); });
try {
  fu.get();
}
catch(const std::runtime_error& e) {
  std::cerr << e.what();
}

On the other hand, since tf::Executor::silent_async does not return any future handle, any exception thrown from a silent-async task will be silently caught by the executor and (1) propagated to the its parent context if one exists or (2) stored locally and ignored if that parent context does not exist.

tf::Taskflow taskflow;
tf::Executor executor;

// exception will be silently ignored
executor.silent_async([](){ throw std::runtime_error("exception"); });

// exception will be propagated to the parent Taskflow
taskflow.emplace([&](tf::Runtime& rt){
  rt.silent_async([](){ throw std::runtime_error("exception"); });
});
try {
  taskflow.get();
}
catch(const std::runtime_error& e) {
  std::cerr << e.what();
}

Example: Catch an Exception from a Corun Loop

When you corun a graph via tf::Executor::corun or tf::Runtime::corun, any exception will be thrown during the execution. For example, the code below will throw an exception during the execution of taskflow1:

tf::Executor executor;
tf::Taskflow taskflow1;
tf::Taskflow taskflow2;

taskflow1.emplace([](){
  throw std::runtime_error("exception");
}); 
taskflow2.emplace([&](){
  try {
    executor.corun(taskflow1);
  } catch(const std::runtime_error& e) {
    std::cerr << e.what();
  }
}); 
executor.run(taskflow2).get();

We can observe the same behavior when using tf::Runtime::corun:

tf::Executor executor;
tf::Taskflow taskflow1;
tf::Taskflow taskflow2;

taskflow1.emplace([](){ throw std::runtime_error("exception"); }); 
taskflow2.emplace([&](tf::Runtime& rt){
  try {
    rt.corun(taskflow1);
  } catch(const std::runtime_error& e) {
    std::cerr << e.what();
  }
}); 
executor.run(taskflow2).get();

For the above example, if the exception is not caught with tf::Runtime::corun, it will be propagated to its parent task, which is the tf::Runtime object rt in this case. Then, the exception will be propagated to taskflow2.

tf::Executor executor;
tf::Taskflow taskflow1;
tf::Taskflow taskflow2;

taskflow1.emplace([&](){ throw std::runtime_error("exception"); }); 
taskflow2.emplace([&](tf::Runtime& rt){ rt.corun(taskflow1); }); 

try {
  executor.run(taskflow2).get();
}
catch(const std::runtime_error& e) {
  std::cerr << e.what();
}

For the above example, if the exception is not caught with tf::Runtime::corun, it will be propagated to its parent task, which is the tf::Runtime object rt in this case. Then, the exception will be propagated to taskflow2.

Retrieve the Exception Pointer of a Task

When multiple tasks throw exceptions simultaneously, some exceptions may not be propagated. In such cases, Taskflow silently catches all unpropagated exceptions and stores them within their respective tasks. To inspect these exceptions, you can use tf::Task::exception_ptr to acquire a pointer to the exception stored in the task, if any. If the task executed without throwing an exception, this method returns nullptr. For example, in the code below, both tasks B and C throw exceptions. However, only one of them will be propagated to the try-catch block, while the other will be silently caught and stored within its respective task.

tf::Executor executor(2); 
tf::Taskflow taskflow;
std::atomic<size_t> arrivals(0);

auto [B, C] = taskflow.emplace(
  [&]() { 
    // wait for two threads to arrive so we avoid premature cancellation
    ++arrivals; while(arrivals != 2);
    throw std::runtime_error("oops"); 
  },
  [&]() { 
    // wait for two threads to arrive so we avoid premature cancellation
    ++arrivals; while(arrivals != 2);
    throw std::runtime_error("oops"); 
  }
);

try {
  executor.run(taskflow).get();
}
catch (const std::runtime_error& e) {
  std::cerr << e.what();
}

// exactly one holds an exception as another was propagated to the try-catch block
assert((B.exception_ptr() != nullptr) != (C.exception_ptr() != nullptr));

Turn off Exception Handling

In some applications, exception handling may not be desirable due to performance concerns, coding style preferences, or platform constraints. Taskflow allows you to disable exception handling entirely at compile time. To do this, define the macro TF_DISABLE_EXCEPTION_HANDLING when compiling your Taskflow program:

# disable exception handling 
~$ g++ -DTF_DISABLE_EXCEPTION_HANDLING your_taskflow_prog.cpp

Disabling exception handling removes all try-catch blocks from the Taskflow runtime, resulting in a leaner binary and potentially faster execution. However, Taskflow will no longer catch or report runtime exceptions.