Table of Contents

Class ExceptionExtensions

Namespace
Cuemon.Extensions
Assembly
Cuemon.Extensions.Core.dll

Extension methods for the Exception class.

public static class ExceptionExtensions
Inheritance
ExceptionExtensions

Examples

ExceptionExtensions.Flatten unwinds deeply nested exception hierarchies into a flat IEnumerable<Exception> while preserving insertion order. This example constructs a four-level exception chain starting with an InvalidOperationException("First") containing AmbiguousMatchException, OutOfMemoryException, and an inner AggregateException with an AccessViolationException. Key setup includes building the nested exception tree and calling Flatten() to produce a flat sequence. Console output shows the count of 4 and each exception type name in order: InvalidOperationException, AmbiguousMatchException, OutOfMemoryException, AccessViolationException.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Cuemon.Extensions;

namespace MyApp.Examples;

public static class ExceptionExtensionsExample
{
    public static void Demonstrate()
    {
        var exception = new InvalidOperationException(
            "First",
            new AmbiguousMatchException(
                "Second",
                new OutOfMemoryException(
                    "Third",
                    new AggregateException(new AccessViolationException("Fourth")))));

        IEnumerable<Exception> flattened = exception.Flatten();

        Console.WriteLine(flattened.Count());
        foreach (var ex in flattened)
        {
            Console.WriteLine(ex.GetType().Name);
        }
    }
}

Methods

Flatten(Exception)

Flattens any inner exceptions from the specified exception into an IEnumerable<T> sequence of exceptions.

public static IEnumerable<Exception> Flatten(this Exception exception)

Parameters

exception Exception

The Exception to extend.

Returns

IEnumerable<Exception>

An empty IEnumerable<T> sequence if no inner exception(s) was specified; otherwise any inner exception(s) chained to the specified exception.

Remarks

If any inner exceptions are referenced, this method will iterative flatten them all from the specified exception.
Should the exception be of the new AggregateException introduced with .NET 4.0, the return sequence of this method will be equal to the result of the InnerExceptions property after a call to Flatten().

Exceptions

ArgumentNullException

exception is null.