Handle a faulted Task’s exception in C#
By FoxLearn 3/20/2025 2:41:59 AM 46
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.
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization