CodeBlanks Logo Icon CodeBlanks

Task.Exception

C# course · Advanced · Lesson 15/83

Learn to inspect task errors with Task.Exception.

The Task.Exception property

The Task.Exception property holds the error as an AggregateException when a Task faults. If the Task has not faulted yet, it returns null. This lets you inspect a Task's error without awaiting it.

This is especially useful in fire-and-forget scenarios or when monitoring many Tasks. Example: if (task.Exception != null) { Log(task.Exception); }. Before the Task completes, this property always returns null.

IsFaulted and Exception

Task.IsFaulted gives a bool indicating whether a Task has faulted. Task.IsCompleted tells if the task is done (including faulted). Task.IsCanceled indicates cancellation.

These three flags let you quickly learn a Task's state. If you need error details, look at the Exception property. In fire-and-forget scenarios you can log by watching these flags.

Exercise Inspect Task.Exception

Define static async Task FailAsync(). In its body write await Task.CompletedTask; and throw new InvalidOperationException("Boom");. Make Main a static async Task Main. Call it with Task t = FailAsync(); (do not await yet). Print IsFaulted with try { await t; } catch (Exception) { Console.WriteLine(t.IsFaulted); }.

Show example solution
In FailAsync body write await Task.CompletedTask; and throw new InvalidOperationException("Boom");. Make Main static async Task Main() and write Task t = FailAsync(); try { await t; } catch (Exception) { Console.WriteLine(t.IsFaulted); }
Example solution:
using System;
using System.Threading.Tasks;

class Program
{
    static async Task FailAsync()
    {
        await Task.CompletedTask;
        throw new InvalidOperationException("Boom");
    }

    static async Task Main()
    {
        Task t = FailAsync();
        try
        {
            await t;
        }
        catch (Exception)
        {
            Console.WriteLine(t.IsFaulted);
        }
    }
}

Test yourself

  1. What does Task.Exception return?

    • AggregateException or null
    • The Exception directly
    • The Task status
    • Bool (whether there is an error)
    Show answer

    AggregateException or null — Correct. Task.Exception returns AggregateException on fault, null otherwise.

  2. Check Task.Exception

    if (task.____ != null) { Console.WriteLine("Hata var"); }
    Show answer
    if (task.Exception != null) { Console.WriteLine("Hata var"); }
  3. When is IsFaulted true?

    • While the Task is still running
    • When the Task has faulted
    • When the Task completes successfully
    • When the Task is cancelled
    Show answer

    When the Task has faulted — Correct. IsFaulted is true only when the task has faulted.

All lessons in Advanced