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 in Taskflow follows a simple yet robust design that ensures program robustness without sacrificing much parallel efficiency. The logic can be understood in three distinct scenarios, depending on how the task is executed and how the runtime is expected to report errors.

TaskflowExceptionHandling ExceptionHandling Exception Handling in Taskflow Scenarios A task throws an exception ExceptionHandling->Scenarios Propagation Scenario 1: Exception propagation through Shared State Scenarios->Propagation Immediate Scenario 2: Immediate exception in blocking execution Scenarios->Immediate Silent Scenario 3: Silent exception suppression Scenarios->Silent

We start with a brief overview of the three scenarios and then examine different use cases in more detail.

Scenario 1: Exception Propagation through Shared State

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 2: Immediate Exception in Blocking Executions

If the taskflow is executed in a blocking context, such as through tf::Executor::corun, exceptions are immediately propagated to the caller.

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

In this scenario, the calling thread becomes the natural exception handler.

Scenario 3: Silent Exception Suppression

In certain cases (e.g., tf::Executor::silent_async), exceptions are silently caught and discarded because there is no associated state or waiting context to report them to. This design ensures the runtime can continue executing other tasks safely without interruption.

executor.silent_dependent_async([](){ 
  throw std::runtime_error("exception won't be caught");
});

Use this form only when failure propagation is intentionally unnecessary (e.g., fire-and-forget logging, telemetry).

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 but are silently 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
}

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

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();
}

Running the program will show the exception message on the async task:

~$ exception

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 task if the parent task exists or (2) ignored if the parent task 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 tf::Runtime task and then its 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();
}

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.