Search⌘ K
AI Features

Exception Catching and Member Functions of Task

Explore how D handles exceptions in multi-threaded tasks by catching and rethrowing them through Task functions. Learn to use yieldForce, spinForce, and workForce methods to manage task execution and completion efficiently.

We'll cover the following...

Exceptions

As tasks are executed on separate threads, the exceptions that they throw cannot be caught by the thread that started them. Therefore, the exceptions that are thrown are automatically caught by the tasks themselves to be rethrown later when Task member functions like yieldForce() are called. This enables the main thread to catch exceptions that are thrown by a task.

D
import std.stdio;
import std.parallelism;
import core.thread;
void mayThrow() {
writeln("mayThrow() is started");
Thread.sleep(1.seconds);
writeln("mayThrow() is throwing an exception");
throw new Exception("Error message");
}
void main() {
auto theTask = task!mayThrow();
theTask.executeInNewThread();
writeln("main is continuing");
Thread.sleep(3.seconds);
writeln("main is waiting for the task");
theTask.yieldForce();
}

The output of the program shows that the uncaught exception that has been thrown by the task does not terminate the entire program right away (it terminates ...