In C#, one check in a multicast Action<string> validation delegate throws; which checks ran, and how do you make every check run?
answer
- targets run in list order
- first throw ends the call
- earlier side effects stay
- one try/catch per target
basics
~20 sTargets before the failing one have run, the failing one throws, and the targets after it never run; the original exception reaches the caller unwrapped. To run every check, invoke each GetInvocationList() entry in its own try/catch and collect the failures.
solid answer
~40 sInvoking a multicast delegate is a plain sequential loop over its invocation list with no error handling. If the second of three checks throws, the first has already run (and kept any side effects), the exception propagates to the caller as the original exception type, not wrapped in an `AggregateException`, and the third check is never called. A validation step built this way reports one failure and hides whether later checks would also have failed. The fix is to take control of the loop: iterate `checks.GetInvocationList()`, cast each entry to `Action<string>`, call it inside its own `try`/`catch`, collect the exceptions, and throw one `AggregateException` or return a result object listing every failure.
code
csharp · 18 linesusing System;
using System.Collections.Generic;
Action<string> checks = sku => Console.WriteLine($"length ok: {sku.Length <= 12}");
checks += sku => { if (!sku.StartsWith("SKU-")) throw new FormatException("bad prefix"); };
checks += sku => Console.WriteLine("currency check ran");
try { checks("ABC-42"); }
catch (FormatException ex) { Console.WriteLine($"caught: {ex.Message}"); } // third check never ran
var failures = new List<Exception>();
foreach (Action<string> check in checks.GetInvocationList())
{
try { check("ABC-42"); }
catch (Exception ex) { failures.Add(ex); }
}
if (failures.Count > 0)
Console.WriteLine($"{new AggregateException(failures).InnerExceptions.Count} check(s) failed");go deeper
Recall that a multicast delegate calls its targets one after another and that an exception stops the call at that target.
Explain that earlier targets have already run, later ones are skipped and the caller sees the original exception, not a wrapper.
Diagnose partial runs from the += order and replace the plain call with a per-target loop that collects every failure when the policy calls for it.
Decide per extension point whether fail-fast or run-all is the contract, and make that explicit in code instead of inheriting the multicast default.
## How a multicast call runs A **multicast delegate** holds an **invocation list**: the methods added with `+=` (which calls `Delegate.Combine`), in the order they were added. Invoking it calls each method **synchronously, in that order, on the caller's thread**. There is no `try`/`catch` around the individual calls. Microsoft's delegate guide puts it plainly: when a method throws an exception that it does not catch, the exception is passed to the caller of the delegate, and no subsequent methods in the invocation list are called. Consider a validation step that combines three checks on a product code: ```csharp Action<string> checks = sku => CheckLength(sku); checks += sku => CheckPrefix(sku); // throws FormatException checks += sku => CheckCurrency(sku); checks("ABC-42"); ``` ## What actually happened 1. `CheckLength` ran to completion. Anything it did (logging, incrementing a counter, writing to a list) **stays done**; nothing is rolled back. 2. `CheckPrefix` threw a `FormatException`. 3. `CheckCurrency` **never ran**. 4. The caller's `catch (FormatException)` sees the **original exception**, with its own stack trace. It is not wrapped in an `AggregateException` or a `TargetInvocationException`. The caller cannot tell from the exception how many targets ran or how many were skipped. For validation, that means the user fixes one problem, resubmits, and only then learns about the next. ## Making every check run The fix is to stop relying on the built-in invocation and loop over the targets yourself: ```csharp var failures = new List<Exception>(); foreach (Action<string> check in checks.GetInvocationList()) { try { check(sku); } catch (Exception ex) { failures.Add(ex); } } if (failures.Count > 0) throw new AggregateException(failures); ``` - `GetInvocationList()` returns a `Delegate[]` with one single-target delegate per entry, in invocation order. - The `foreach` iteration type casts each entry back to `Action<string>`, so the call is strongly typed. - Collecting exceptions and throwing one `AggregateException` (or returning a validation result object) reports **every** failure in one pass. - If failures are expected rather than exceptional, consider changing the shape entirely: checks that **return** an error message instead of throwing are cheaper and easier to aggregate. In that case, loop over the invocation list for the same reason a multicast `Func` would otherwise return only the last check's result. ## Choosing a policy | Policy | How | When it fits | |---|---|---| | Stop at first failure | plain multicast call | fail-fast pipelines where later steps depend on earlier ones | | Run all, report all | loop with per-target try/catch | input validation, plug-in notifications | | Run all, log and continue | loop, log each exception, do not rethrow | best-effort side effects such as metrics | The built-in behaviour is not wrong; it is simply the fail-fast policy. The bug is choosing it by accident. ## Catching inside each target instead Another option is to make every check catch its own exceptions and record the failure somewhere shared, so the multicast call itself never sees an exception. That works, but it moves the policy into every target: one check written without a `try`/`catch` restores the fail-fast behaviour for every check after it, and the shared failure list becomes hidden state the caller has to know about. Owning the loop in one place keeps the policy visible: - the caller decides fail-fast versus run-all; - the targets stay simple and can throw or return a result; - tests can assert the full list of failures from one call. ## Diagnosing it in production - A symptom such as "the audit entry is written but the currency check never logs" points to an earlier target throwing. - Check the **order** of `+=` calls: the targets after the thrower are the ones that silently did not run. - Check whether some caller catches and swallows the exception, which turns a partial run into a silent one. Events raise their subscribers through the same mechanism, so the same reasoning applies to a subscriber that throws; that case, and how event publishers guard against it, is covered with the event pattern.
- Does a multicast call wrap the failing target's exception in a TargetInvocationException?No. A normal delegate invocation is a direct call, so the exception propagates with its original type and stack trace. `TargetInvocationException` wrapping comes from late-bound calls such as `Delegate.DynamicInvoke` or `MethodInfo.Invoke`, which go through reflection-style invocation.
- If you switch the checks to Func<string, bool> and keep the multicast call, what changes?Nothing throws any more, but the call returns only the last check's bool, so a failing first check is silently ignored. Value-returning checks still need a loop over `GetInvocationList()` that evaluates each result, or a collection of checks instead of one combined delegate.
- The runtime wraps multicast failures in an AggregateException holding every error
- The remaining targets still run and the exception is rethrown at the end
- Targets that already ran are rolled back when a later target throws
- Multicast targets run in parallel, so the failing one cannot stop the others
- A try/catch around the multicast call lets the later targets continue