C# › Exception Handling
How does exception performance (throwing/catching) compare to normal control flow, and why should exceptions generally NOT be used for expected, routine control flow?
AdvancedAnswer
Throwing an exception involves capturing a full stack trace and unwinding the call stack, which is SIGNIFICANTLY more expensive (often orders of magnitude slower) than a normal return value or conditional check — exceptions should be reserved for genuinely EXCEPTIONAL, unexpected conditions, not routine logic like 'no results found,' which should instead use return values (like a nullable result, or the Result<T,E> pattern).
// Expensive anti-pattern: using exceptions for expected, routine 'not found' logic
try {
var user = repository.GetByIdOrThrow(id); // throws routinely when not found
} catch (NotFoundException) { return null; }
// Better: use a return value for an expected, routine outcome
var user = repository.TryGetById(id); // returns null, no exception overheadReal-world example Refactoring a hot-path lookup method that routinely 'fails' (like a cache miss) to avoid the real performance cost of exception-based control flow.