Handle a faulted Task’s exception in C#

By FoxLearn 3/20/2025 2:41:59 AM   46
When a Task throws an exception and ceases execution, it becomes "faulted." The key question is: how do you access the exception thrown by a faulted Task?

This article explains how to handle exceptions from a faulted Task in two scenarios: when you are awaiting the Task and when you are not.

Handling Exceptions for a Non-Awaited Task

Imagine you start a background task but don't await it. This task might be doing something like monitoring the file system for changes. When it encounters an error, you want to handle the fault. In this example, we’ll log the root cause of the exception.

To manage the exception, use the ContinueWith() method to add a continuation that specifies the TaskContinuationOptions.OnlyOnFaulted option. This ensures the continuation is only executed if the Task encounters an exception.

The exception on the continuation task is wrapped in an AggregateException. To access the root cause, use GetBaseException().

Task.Run(BackgroundTask).ContinueWith(t =>
{
    var ex = t.Exception?.GetBaseException();
    if (ex != null)
    {
        Logger.Error($"Task faulted and stopped running. ErrorType={ex.GetType()} ErrorMessage={ex.Message}");
    }
},
TaskContinuationOptions.OnlyOnFaulted);

In this example, I intentionally throw an exception in the background task, and the output will be:

Task faulted and stopped running. ErrorType=System.NotFiniteNumberException ErrorMessage=Number encountered was not a finite quantity.

Handling Exceptions for an Awaited Task

If you're able to await the task, it's much simpler. You can wrap the await call in a try/catch block. When the Task faults, the framework automatically unwraps the AggregateException, allowing you to handle the original exception.

try
{
    await BackgroundTaskAsync();
}
catch (Exception ex)
{
    Logger.Error($"Task faulted and stopped running. ErrorType={ex.GetType()} ErrorMessage={ex.Message}");
}

When you run this code, the output will be:

Task faulted and stopped running. ErrorType=System.NotFiniteNumberException ErrorMessage=Number encountered was not a finite quantity.

In both cases, handling exceptions in faulted tasks helps you log and respond to errors gracefully, ensuring your application can manage failures effectively.