C# and .NET • Modern C# baseline
Exceptions and Failure Boundaries
Use exceptions for exceptional failures and handle them at a boundary that can recover or report.
Exceptions unwind the call stack and execute finally blocks and disposal logic. Catch specific exception types when the code can recover meaningfully. Avoid catching Exception broadly just to continue with a success-shaped fallback, and do not use exceptions for ordinary branching when a result type is clearer.
Key points
- Preserve the original exception when adding context.
- Log an exception once at the boundary that owns the response.
Example
try
{
int number = int.Parse("not-a-number");
Console.WriteLine(number);
}
catch (FormatException error)
{
Console.Error.WriteLine($"Invalid number: {error.Message}");
}
What to expect
The format error is handled and an explanatory message is written to standard error.
Practice exercise
Replace Parse with TryParse and compare which behavior best fits routine user input.
Key idea: A catch block should recover, translate, or report—not hide a failure.