In .NET, when should a throwing method such as Postcode.Parse get a TryParse companion, and what must that Try method still throw?
answer
- expected failure or broken contract
- bool return, out parameter
- one well-defined failure only
- misuse still throws
- a throw allocates and walks the stack
basics
~20 sAdd a TryX companion when callers routinely hit one expected failure, such as malformed input in an import: it returns false and leaves the out value at default instead of throwing. It still throws for any failure outside that defined case.
solid answer
~40 sThe .NET convention is a pair: `Parse(string)` throws (`FormatException` for bad text) and `TryParse(string?, out T result)` returns `bool`, leaving `result` at `default` when it fails. Offer the Try form when the failure is an outcome the caller will branch on, such as a file of typed-in postcodes, because a throw allocates an exception object, walks the stack to find a handler and records the trace, which costs far more than returning `false` in a loop that fails thousands of times. The Try method covers one well-defined failure only: `int.TryParse` returns `false` for `null`, bad text or overflow, yet still throws `ArgumentException` for an invalid `NumberStyles`, and `Dictionary<TKey,TValue>.TryGetValue` throws `ArgumentNullException` for a null key. Keep the throwing member too, and mark the out parameter `[NotNullWhen(true)]` so nullable analysis knows when it is set.
code
csharp · 38 linesusing System.Diagnostics.CodeAnalysis;
string[] rows = new string[10_000];
for (int i = 0; i < rows.Length; i++)
rows[i] = i % 2 == 0 ? $"{10000 + i}" : "not-a-postcode";
long before = GC.GetAllocatedBytesForCurrentThread();
int bad1 = 0;
foreach (var row in rows)
{
try { Postcode.Parse(row); }
catch (FormatException) { bad1++; }
}
long throwBytes = GC.GetAllocatedBytesForCurrentThread() - before;
before = GC.GetAllocatedBytesForCurrentThread();
int bad2 = 0;
foreach (var row in rows)
if (!Postcode.TryParse(row, out _)) bad2++;
long tryBytes = GC.GetAllocatedBytesForCurrentThread() - before;
Console.WriteLine($"Parse + catch: {bad1} rejected, {throwBytes / 1024} KB allocated");
Console.WriteLine($"TryParse: {bad2} rejected, {tryBytes / 1024} KB allocated");
sealed record Postcode(int Value)
{
public static Postcode Parse(string s)
{
ArgumentNullException.ThrowIfNull(s);
return TryParse(s, out var p) ? p : throw new FormatException($"'{s}' is not a postcode.");
}
public static bool TryParse([NotNullWhen(true)] string? s, [NotNullWhen(true)] out Postcode? result)
{
result = int.TryParse(s, out int v) && v is >= 10000 and <= 99999 ? new Postcode(v) : null;
return result is not null;
}
}go deeper
Recall the pair: Parse throws on bad input, TryParse returns false and gives the value through an out parameter. Use TryParse when bad input is expected.
Explain the contract: false only for the one defined failure, default in the out parameter, still throws for misuse, and [NotNullWhen(true)] on the out value.
Spot exceptions used as control flow on a hot path, explain what a throw costs (allocation, stack walk, trace capture) and measure it with allocation counters rather than a single timing.
Set the library rule for which operations get a Try companion and which failures must stay exceptions, so callers across services read failures the same way.
## Two shapes of one operation .NET reports failures with exceptions, but some failures are not exceptional at all: a user mistypes a postcode, a cache does not hold a key yet. For those, the base class library pairs a throwing member with a **Try** member: | Member | On success | On the expected failure | Example | |---|---|---|---| | `Parse(string)` | returns the value | throws `FormatException` | `int.Parse("abc")` | | `TryParse(string?, out T)` | returns `true`, sets the out value | returns `false`, out value is `default` | `int.TryParse("abc", out var n)` | | indexer `dict[key]` | returns the value | throws `KeyNotFoundException` | a missing key | | `TryGetValue(TKey, out TValue)` | returns `true` | returns `false` | the same missing key | The design guidelines call this the **Try-Parse pattern**: the name starts with `Try`, the method returns `bool`, the result comes back through an `out` parameter, and a throwing member exists beside it. ## When the Try form earns its place - **The failure is an expected outcome.** An address importer reads thousands of rows and some will be malformed; that is data, not a bug. - **The caller can do something useful with `false`.** It skips the row, asks the user again, or falls back to a default. - **The failure rate is high or the path is hot.** A parse loop, a cache lookup, per-request validation. - **No Try form** is needed when failure means a bug or an environment problem the caller cannot prevent; a `LoadRates()` that cannot reach its file should simply throw. The other option the guidelines describe is **Tester-Doer**: a cheap test before the call, such as checking `ICollection<T>.IsReadOnly` before `Add`. It reads well but splits one operation into two calls, so another thread or process can change the answer in between; the Try form is a single call. ## The contract a Try method must keep 1. **Define the try case strictly.** `false` means exactly the expected failure, such as text that is not a valid postcode. 2. **Throw for everything else.** The guidelines say a Try member that fails for any other reason must still throw. `int.TryParse("1", (NumberStyles)0x10000, null, out _)` throws `ArgumentException`, and `Dictionary<TKey,TValue>.TryGetValue(null, out _)` throws `ArgumentNullException`: both are caller bugs, not expected outcomes. 3. **Set the out parameter to `default` on failure.** The compiler already requires an `out` parameter to be assigned on every return path; the convention says what to assign. 4. **Annotate nullability.** `[NotNullWhen(true)] out Postcode? result` tells the compiler the value is non-null after a `true` return. The BCL annotates its own Try methods the same way: `int.TryParse` marks its string input `[NotNullWhen(true)]`, and `Dictionary<TKey,TValue>.TryGetValue` marks its out value `[MaybeNullWhen(false)]`. 5. **Keep the throwing member** for callers who treat the failure as a bug; it can simply call the Try method and throw when it returns `false`. ## What a throw actually costs A `return false` is a branch. A `throw` is much more work: - an **exception object** is allocated, often with a formatted message string; - the runtime **walks the stack** to find a matching handler, running any exception filters on the way; - it **records the frames** that make up `StackTrace` and runs `finally` blocks as it unwinds; - diagnostics such as the first-chance exception notification and debugger events fire. The design guidelines add that members containing a `throw` do not get inlined, which is why the BCL moves throws into helper methods. .NET 9 replaced CoreCLR's exception handling with the model NativeAOT uses and measured it 2 to 4 times faster in micro-benchmarks; a throw is still far costlier than a `bool` return. Measured with `GC.GetAllocatedBytesForCurrentThread()` around 10,000 rows, half of them malformed, `Parse` plus `catch` allocated about 2 MB on .NET 10 while `TryParse` allocated about 117 KB, which is only the `Postcode` objects for the good rows. ## The quote library's version ```csharp public static bool TryParse([NotNullWhen(true)] string? s, [NotNullWhen(true)] out Postcode? result) { result = int.TryParse(s, out int v) && v is >= 10000 and <= 99999 ? new Postcode(v) : null; return result is not null; } public static Postcode Parse(string s) { ArgumentNullException.ThrowIfNull(s); return TryParse(s, out var p) ? p : throw new FormatException($"'{s}' is not a postcode."); } ``` `TryParse` accepts `null` and returns `false`, like `int.TryParse`; `Parse` treats `null` as a bug and bad text as a `FormatException`. The importer calls `TryParse` and counts rejects; code that has already validated its input calls `Parse` and lets a surprise surface loudly.
- Why not make TryParse catch every exception internally and return false?Then a caller bug, such as an invalid `NumberStyles` value, would look like ordinary bad input and be silently skipped. The guidelines require the Try member to return `false` only for its one well-defined failure and to throw for anything else, which is what `int.TryParse` and `Dictionary<TKey,TValue>.TryGetValue` do. Catching inside would also keep paying the cost of the throw that the Try form exists to avoid.
- Is checking a condition first, then calling the throwing method, just as good as a Try method?That is the Tester-Doer pattern, such as checking `ICollection<T>.IsReadOnly` before `Add`. It avoids the throw in the common case but makes two calls, so on shared state the condition can change between the test and the call and the doer can still throw. A Try method does the check and the work in one call, which is why hot or shared paths prefer it.
- Why can a Try method not be async in C#?C# does not allow `ref`, `in` or `out` parameters on async methods (error CS1988), so `bool TryX(out T)` cannot become `Task<bool> TryXAsync(out T)`. Async APIs return the outcome instead, for example a `Task<T?>` that is `null` on failure or a small result type.
- Wraps Parse in try/catch inside a loop that expects bad rows
- Makes TryParse swallow every exception and return false
- Thinks a Try method should never throw under any input
- Leaves the out parameter unannotated so callers need the ! operator
- Removes the throwing Parse because TryParse exists
Assumes .NET 10; .NET 9 moved CoreCLR to the NativeAOT-based exception handling model, faster in micro-benchmarks, yet a throw still costs far more than returning false.