A C# iterator wraps yield return int.Parse(row) in try/catch and fails with CS1626; why, and how do you restructure it to skip bad rows?
answer
- a catch cannot wrap a pause
- try with only finally is fine
- move the try into a helper
- yield break is still allowed
- C# 13 relaxed ref locals
basics
~20 sC# forbids yield return inside a try block that has a catch (CS1626) and inside a catch block (CS1631). Move the try/catch into an ordinary helper that parses one row and reports success, then yield outside the try.
solid answer
~50 sIt is a language rule on iterators: `yield return` may sit in a `try` that has only a `finally` (so `using` works), but not in a `try` with a `catch` (CS1626) or inside a `catch` (CS1631), and no `yield` at all may appear in a `finally` (CS1625); `yield break` is still allowed in a `try` with a `catch` and in a `catch`. The fix is to move the risky call into a non-iterator helper, say `int? TryParseRow(string)`, that catches `FormatException` for one row, and to `yield return` only successful results outside any `try`. The iterator stays lazy because rows are still parsed one at a time. For integers, `int.TryParse` avoids the exception entirely. Other iterator restrictions: no `ref`, `in` or `out` parameters (CS1623); `ref` locals and `unsafe` blocks only from C# 13; and no `ref` or span local used across a `yield return`.
code
csharp · 16 linesforeach (var r in Parse(["1", "x", "3"])) Console.WriteLine(r);
static IEnumerable<int> Parse(string[] rows)
{
foreach (string row in rows)
{
try
{
yield return int.Parse(row);
}
catch (FormatException)
{
Console.WriteLine($"skipped {row}");
}
}
}go deeper
Recall that a yield return cannot sit inside a try that has a catch, while try with finally, and using, are fine inside iterators.
Explain the full placement table: CS1626 for try with catch, CS1631 for catch, CS1625 for finally, and that yield break is allowed in the first two.
Restructure without losing laziness by moving the risky call into a helper, prefer TryParse-style APIs where they exist, and know that C# 13 allows ref locals and unsafe blocks only between yields.
Treat the rule as a design pressure: keep iterators thin, push error handling into small helpers, and agree how a streaming pipeline reports bad rows rather than swallowing them.
## The error A common first attempt at a parser that skips bad rows looks like this: ```csharp static IEnumerable<int> Parse(string[] rows) { foreach (string row in rows) { try { yield return int.Parse(row); } catch (FormatException) { Console.WriteLine($"skipped {row}"); } } } ``` It does not compile. The SDK reports **CS1626**: "Cannot yield a value in the body of a try block with a catch clause". ## What the rule says The restriction is a C# language rule the compiler enforces, not something the runtime makes impossible: async methods, which the compiler also rewrites into state machines, allow `await` inside a `try` block that has a `catch`, and since C# 6 even inside the `catch` and `finally` blocks themselves. For iterators, the rules on where `yield` may appear are: | Placement | `yield return` | `yield break` | |---|---|---| | `try` block with only a `finally` | allowed | allowed | | `try` block with a `catch` | CS1626 | allowed | | `catch` block | CS1631 | allowed | | `finally` block | CS1625 | CS1625 | So `try`/`finally` and `using` work around `yield return`, which is what lets an iterator clean up resources. A `catch` cannot wrap a `yield return`. Note the wording of the diagnostics: CS1626 and CS1631 are about yielding a *value*, and the SDK 10.0.401 compiler accepts `yield break` in both places; only `finally` forbids both forms. Some documentation pages state the rule more broadly than the compiler enforces it. It also helps to see what such a `catch` could never do even if it were allowed: the consumer's loop body runs between `MoveNext()` calls, outside the iterator, so a `catch` around `yield return` could only ever see exceptions from the iterator's own code. ## How to restructure it Move the code that can throw into an ordinary method, and keep every `yield return` outside any `try` that has a `catch`: 1. Write a non-iterator helper that does the risky work for **one** row inside `try`/`catch` and reports success, for example by returning `int?` or using a `bool` result with an `out` parameter. 2. In the iterator, call the helper per row and `yield return` only the successful results. 3. The iterator stays lazy: rows are still parsed one at a time, as the consumer asks for them. ```csharp static IEnumerable<int> ParseAll(string[] rows) { foreach (string row in rows) { if (TryParseRow(row) is int value) yield return value; } } static int? TryParseRow(string row) { try { return int.Parse(row); } catch (FormatException) { return null; } } ``` For integers specifically, `int.TryParse(string, out int)` avoids the exception altogether and is the better choice; the helper pattern is for work that genuinely throws, such as a third-party parser. Avoid the tempting alternative of parsing every row into a `List<int>` inside one big `try`/`catch` and then yielding from the list: it compiles, but it reads the whole input up front and stops being lazy. ## The other iterator restrictions - **No `ref`, `in` or `out` parameters**: CS1623, "Iterators cannot have ref, in or out parameters". The body runs later, inside `MoveNext()` on a heap object, so it cannot hold a reference to the caller's variable. - **No `return` statement**: CS1622, even a bare `return;`. - **No `yield` in a lambda or anonymous method**: CS1621. A local function can be an iterator. - **Ref locals and `unsafe` blocks, from C# 13**: an iterator may declare a `ref` local and contain an `unsafe` block only from C# 13; under `LangVersion` 12 the .NET 10 SDK reports CS9202 for either. Even now, a `ref` local or a `ref struct` local such as a `Span<T>` is allowed **only as long as it is not used across a `yield return`**, because it can never be hoisted into the state machine's heap fields. Reading a `ReadOnlySpan<char>` after a `yield return` fails with CS4007, and using a `ref` local after one fails with CS9217. A `yield return` inside an `unsafe` block is CS9238. ## What interviewers look for A senior answer names the diagnostic, states the rule precisely (a `catch` cannot wrap a `yield return`; a `finally` can), restructures without losing laziness, and knows that the C# 13 relaxation is about locals that do not cross a `yield`, not a general lifting of iterator rules.
- Is yield break allowed inside a try block with a catch, or inside a catch, in a C# iterator?Yes. CS1626 and CS1631 are about yielding a value; the .NET 10 SDK's compiler accepts `yield break` inside a `try` that has a `catch` and inside the `catch` itself, ending the sequence there. Only a `finally` block forbids both forms (CS1625). Some documentation states the rule more broadly than the compiler enforces it.
- Since C# 13, can an iterator use a ref local or a Span<T> local?Yes, provided the variable is not used across a `yield return`, so it never has to be hoisted into the state machine. Using a `ref` local after a `yield return` fails with CS9217 and reading a span after one with CS4007. `ref` locals need C# 13 (CS9202 under `LangVersion` 12), and parameters still cannot be `ref`, `in` or `out` (CS1623).
- Why can't a C# iterator take a ref or out parameter?Its body runs later, inside `MoveNext()` on a heap-allocated state machine, after the method has already returned, so it cannot keep a reference to the caller's variable, and an `out` value could not be assigned before the method returns. The compiler reports CS1623, "Iterators cannot have ref, in or out parameters".
- yield return is forbidden in every try block, even one with only finally
- A catch around yield return would also catch the consumer's exceptions
- yield break is just as forbidden inside a catch as yield return
- C# 13 removed every iterator restriction on spans and ref locals
- Buffering all rows into a list first is the clean lazy fix
Assumes C# 14 on .NET 10; ref locals and unsafe blocks in iterators need C# 13 or later, and a ref or span local still must not be used across a yield return.