Part 07 of a hands-on C# practice series. Four runnable, heavily commented examples: precise try/catch/finally mechanics (finally vs return, stack unwinding), exception filters (when) including the log-without-catching trick, throw; vs throw e; proven with stack traces, custom exception design done right, and a measured demonstration of why TryParse beats Parse+catch for expected failures.
dotnet run # all examples
dotnet run 2 # just one (e.g. filters)| # | Topic | Highlights |
|---|---|---|
| 01 | Mechanics | top-down catch matching, finally with return, unwinding, cost model |
| 02 | Filters & rethrow | catch...when, log-and-keep-flying, throw; vs throw e; proven live |
| 03 | Custom exceptions | type-as-API, data as properties, InnerException chains, when NOT to |
| 04 | Best practices | empty-catch crime scene, Parse vs TryParse measured, guards, global handler |
- Never swallow — log and rethrow (
throw;, neverthrow e;). - Expected failure?
TryXxx/Result<T>. Exceptional failure? Exception. - Catch only what you can handle; one global handler catches the rest.
- Guard clauses throw next to the bug (
ArgumentException.ThrowIfNullOrWhiteSpace). - Custom exception only when a caller handles that case differently — and then: data as properties, wrap causes as
InnerException.
← Previous: 06 Types & memory · Next: 08 Modern C# 8–12 →
| Part | Topic |
|---|---|
| 01 | Collections |
| 02 | LINQ |
| 03 | Delegates & events |
| 04 | Async/await |
| 05 | Generics |
| 06 | Types & memory |
| 07 | Exceptions (this repo) |
| 08 | Modern C# 8–12 |
| 09 | Strings & text |
| 10 | Files & JSON |
| 11 | MiniShop microservices (finale) |
Matej Zlatunić
Released under the MIT License. Feel free to use it for learning.