QuickDevGuide

Home › C#

Exceptions — C#

Handling try / catch / finally, with the most specific catch first. Exception filters (catch (HttpRequestException e) when (e.StatusCode == 404)) catch only when a condition holds, without unwinding the stack. Throwing Use guard helpers: ArgumentNullException.ThrowIfNull(x), ArgumentException.ThrowIfNullOrEmpty(s), ArgumentOutOfRangeException.ThrowIfNegative(n). Re-throw with throw; (keeps the stack trace) — never throw ex;. Wrap with context: throw new OrderException("…", ex) (inner exception preserved). Resource clean-up using var stream = File.OpenRead(path); disposes at the end of the scope; await using for IAsyncDisposable. Guidelines Do not use exceptions for normal control flow (use TryParse, TryGetValue). In ASP.NET Core, convert unhandled exceptions to ProblemDetails responses…

Key Takeaways