C#

Exception Handling

6 question(s)

What is the difference between throw and throw ex inside a catch?

Beginner
throw re-throws preserving the original stack trace; throw ex resets the stack trace to the current line, losing where the error really happened.
catch (Exception ex) { Log(ex); throw; }      // good
catch (Exception ex) { throw ex; }             // loses stack trace
Real-world example Preserving the original stack trace is essential for diagnosing production errors.

What is the purpose of the finally block?

Beginner
finally always runs (whether or not an exception occurred) and is used to release resources like files, connections or locks.
try { conn.Open(); ... }
finally { conn.Dispose(); }
Real-world example Ensuring a database connection is closed even if the query throws.

When should you use using or await using?

Intermediate
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.

What are exception filters (when) and why use them?

Intermediate
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.

When should you create custom exceptions vs use built-in ones?

Advanced
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.

What is the recommended strategy for exceptions in a layered/enterprise app?

Advanced
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.