Advertisement
Advanced C#, Exception Handling

What is 'exception filtering with side effects' and why is it considered a controversial but sometimes useful technique for logging?

Short answer

Since a 'when' filter's condition is evaluated BEFORE deciding whether to catch, you can put a logging call inside the filter expression itself (returning true always) to log EVERY exception as it passes through — even ones that ultimately AREN'T caught by this particular block…

Save C# mock interview
Advertisement
AModel answer
Since a 'when' filter's condition is evaluated BEFORE deciding whether to catch, you can put a logging call inside the filter expression itself (returning true always) to log EVERY exception as it passes through — even ones that ultimately AREN'T caught by this particular block — though many consider embedding side effects in a filter condition a code smell, since it obscures the filter's true purpose.
try {
  DoWork();
} catch (Exception ex) when (LogAndReturnFalse(ex)) {
  // never actually reached, since LogAndReturnFalse always returns false
}

bool LogAndReturnFalse(Exception ex) {
  Console.WriteLine($"Observed (but not handled): {ex.Message}");
  return false; // lets the exception continue propagating after logging
}
Real-world example
Globally logging every exception that passes through a certain layer of code, even ones ultimately handled elsewhere further up the call stack.
Likely follow-ups
  • What's a cleaner, less surprising alternative to achieve the same 'log everything, handle selectively' goal?
Related topics