For IDisposable/IAsyncDisposable resources — they call Dispose/DisposeAsync deterministically at the end of scope, even on exceptions, replacing manual try/finally.
await using var conn = new SqlConnection(cs);
await conn.OpenAsync();
Real-world example
Guaranteeing a stream or connection is released promptly rather than waiting for GC.
A when clause lets a catch run only if a condition is true, without unwinding the stack for non-matching cases, which aids logging and selective handling.
catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { }
Real-world example
Handling only 404s from an HTTP call while letting other status codes propagate.
Create a custom exception when callers need to catch a domain-specific condition distinctly; otherwise reuse built-ins (ArgumentException, InvalidOperationException). Keep a meaningful hierarchy.
public class InsufficientFundsException(decimal shortfall) : Exception;
Real-world example
A banking layer throws InsufficientFundsException so the API can map it to a 422 response.
Throw specific exceptions in lower layers, don't swallow them, translate to a consistent response at the boundary (middleware/ProblemDetails), and log with context. Avoid using exceptions for control flow.
app.UseExceptionHandler(); // central translation to ProblemDetails
Real-world example
One middleware converts domain and unexpected exceptions into consistent JSON errors for all API clients.
Code in the try block runs normally; if it throws, execution jumps immediately to the FIRST matching catch clause (matched by exception type, checked top to bottom) — if no catch clause matches the thrown exception's type, the exception propagates up the call stack, potentially crashing the program if never caught anywhere.
Code in a finally block ALWAYS runs after the try (and any catch) block completes, whether an exception was thrown or not, and even if the try block contains a 'return' statement — making it the standard place for cleanup code like closing files or releasing resources.
FileStream? file = null;
try {
file = File.OpenRead("data.txt");
ProcessFile(file);
} finally {
file?.Dispose(); // always runs, ensuring the file handle is released
}
Real-world example
Guaranteeing a database connection or file handle is properly closed regardless of whether the operation succeeded or threw.
Likely follow-ups
How does the 'using' statement relate to and often replace a manual try/finally for disposal?
A custom exception should inherit from Exception (or a more specific built-in exception type), be named ending in 'Exception', and typically provide the standard set of constructors (parameterless, message-only, message+innerException) to remain compatible with standard exception-handling conventions and serialization.
public class InsufficientFundsException : Exception {
public decimal ShortfallAmount { get; }
public InsufficientFundsException(decimal shortfall)
: base($"Insufficient funds. Short by {shortfall:C}.") {
ShortfallAmount = shortfall;
}
}
Real-world example
Throwing a domain-specific exception (like InsufficientFundsException) that carries meaningful business context beyond a generic message string.
Likely follow-ups
Why is it considered good practice to include the standard set of base constructors on a custom exception?
The 'when' clause adds a condition to a catch block that must ALSO be true for that catch to handle the exception — critically, if the condition is false, the exception continues propagating WITHOUT the catch block ever executing, preserving the original stack trace exactly, unlike catching broadly and manually re-throwing based on a condition inside.
try {
await CallApiAsync();
} catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.TooManyRequests) {
await Task.Delay(1000);
await RetryAsync();
}
// Exceptions NOT matching the 'when' condition propagate normally, untouched
Real-world example
Handling only a SPECIFIC HTTP status code's exception (like rate limiting) while letting all other HttpRequestExceptions propagate normally.
Likely follow-ups
How does exception filtering with 'when' avoid the stack-trace-resetting problem of catch-then-rethrow?