跳到主要内容

Exceptions in C#

Short, interview-ready summary of exception handling.


Memory hook

"try = run code; catch = handle; finally = always run; throw = raise"


try / catch / finally

try
{
DoWork();
}
catch (ArgumentException ex)
{
Log(ex);
throw; // rethrow, preserves stack trace
}
catch (Exception ex)
{
Log(ex);
throw new InvalidOperationException("Wrapped", ex);
}
finally
{
Cleanup(); // runs even on throw or return
}
  • catch order: most specific first (e.g. ArgumentException before Exception)
  • throw; rethrows original; throw ex; resets stack trace (avoid)
  • finally runs on normal exit, return, or exception

throw expressions (C# 7+)

string name = value ?? throw new ArgumentNullException(nameof(value));
int n = x > 0 ? x : throw new ArgumentException("Must be positive");

Custom exception

public class MyAppException : Exception
{
public MyAppException() { }
public MyAppException(string message) : base(message) { }
public MyAppException(string message, Exception inner) : base(message, inner) { }
}
throw new MyAppException("Something failed");
  • Prefer inheriting Exception (or a standard subtype)
  • Include message and optional inner exception

When to throw

  • Invalid arguments → ArgumentException / ArgumentNullException
  • Invalid state → InvalidOperationException
  • Not found → KeyNotFoundException or custom
  • Avoid using exceptions for normal control flow (e.g. expected “not found”)

When to catch

  • At layer boundaries (e.g. API, UI) to log and return friendly response
  • When you can recover or translate (e.g. retry, fallback)
  • Avoid swallowing: either handle, rethrow, or wrap

Interview one-liner

"Use try/catch for exceptional, unexpected failures. Catch specific types first; use throw; to rethrow without losing the stack trace. Finally runs always. Prefer custom exceptions for domain errors; use standard types (ArgumentNullException, InvalidOperationException) where they fit."


Cheat sheet

try / catch (specific first) / finally
throw; = rethrow (keep stack)
throw ex; = reset stack (avoid)
Custom exception : Exception
Catch at boundaries; don’t swallow