namespace tf {

/** @page ExceptionHandling Exception Handling

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

@tableofcontents

@section UnderstandTheLogicOfExceptionHandlingInTaskflow 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.

@dotfile images/exception-handling-logic.dot

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.

@subsection Secnario1SynchronousExceptionPropagation 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.

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

@subsection Scenario2AsynchronousExceptionPropagation 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.

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



@subsection Scenario3ContextualExceptionPropagation  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.

@code{.cpp}
// 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(); 
  }
});
@endcode


@subsection ExceptionHandlingAlgorithmFlow 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.

@dotfile images/exception-handling-algorithm.dot


@section CatchAnExceptionFromARunningTaskflow 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 @c get method:

@code{.cpp}
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;
}
@endcode

@attention
As tf::Future is derived from @std_future, it inherits all the exception handling
behaviors defined by the C++ standard.

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, @c A and @c B, where @c B runs after @c A.
If @c A throws an exception, the executor cancels the remaining execution of the taskflow, 
preventing any dependent tasks (including @c B) from running.

@code{.cpp}
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;
}
@endcode

@code{.bash}
~$ exception on A
# execution of taskflow is cancelled after an execution is thrown
@endcode

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 @c B and task @c C may throw exceptions concurrently. 
Only one exception, either from task B or task C, will be propagated.
  
@code{.cpp}
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
}
@endcode

@section CatchAnExceptionFromASubflow 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`:

@code{.cpp}
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();
@endcode

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:

@code{.bash}
Task A
exception thrown during subflow joining: exception on A
@endcode

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.

@code{.cpp}
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();
}
@endcode

@code{.bash}
Task A
exception thrown from running the taskflow: exception on A
@endcode


@section CatchAnExceptionFromAnAsyncTask 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.

@code{.cpp}
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();
}
@endcode

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.

@code{.cpp}
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();
}
@endcode

@section CatchAnExceptionFromACorunLoop 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`:

@code{.cpp}
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();
@endcode

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

@code{.cpp}
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();
@endcode

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`.

@code{.cpp}
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();
}
@endcode

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`.

@section RetrieveTheExceptionPointerOfATask 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.
    
@code{.cpp}
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));
@endcode

@section TurnOffExceptionHandling 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:

@code{.bash}
# disable exception handling 
~$ g++ -DTF_DISABLE_EXCEPTION_HANDLING your_taskflow_prog.cpp
@endcode

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.

@attention
Disabling exception handling means that any exception thrown during execution will be unchecked,
which may cause your program to behave unpredictably.
Use this option only if your application does not rely on exception safety.

*/

}



*/

}


