Exception filters

A catch with when

A when clause adds a condition to a catch: the block runs only if the type matches and the condition is true. The condition is an ordinary boolean expression over the exception, so the catch can be about the state of the error and not only its class:

try { Fail("disk"); } catch (Exception e) when (e.Message == "disk") { Console.WriteLine("disk catch"); } catch (Exception e) { Console.WriteLine($"other: {e.Message}"); } Console.WriteLine("done"); static void Fail(string reason) => throw new Exception(reason);

dotnet run

disk catch
done

Both catches name Exception, which would be a compile error without the filter, because the second could never run. The filter makes the first catch narrower than its type, and the compiler accepts the pair. A filter that is false moves on to the next catch, exactly as a type mismatch does.

A filter that logs and declines

The condition may call a method, and that method may have a side effect. This is the idiom for logging an exception without swallowing it: the filter logs and returns false, so the exception continues to the next handler:

try { try { Fail(2); } catch (Exception e) when (Log(e)) { Console.WriteLine("caught inner"); } } catch (Exception e) { Console.WriteLine($"outer {e.Message}"); } Console.WriteLine("done"); static bool Log(Exception e) { Console.WriteLine($"log {e.Message}"); return false; } static void Fail(int code) => throw new Exception($"code {code}");

dotnet run

log code 2
outer code 2
done

caught inner never printed, because the filter said no after logging. Doing the same with a catch that logs and then throw; is close, but not identical: a filter runs before the stack is unwound, so the exception keeps its original trace and the frames below are untouched. That is why a diagnostic filter is cheaper and more faithful than a catch that rethrows.

Filters and the order of the catches

Each catch is tried in order: the type first, then the filter. A custom exception with a status code makes the rule visible:

Handle(new HttpError(404)); Handle(new HttpError(500)); Handle(new HttpError(301)); Console.WriteLine("done"); static void Handle(HttpError error) { try { throw error; } catch (HttpError e) when (e.Status == 404) { Console.WriteLine("not found"); } catch (HttpError e) when (e.Status >= 500) { Console.WriteLine("server error"); } catch (HttpError e) { Console.WriteLine($"other {e.Status}"); } } class HttpError(int status) : Exception($"status {status}") { public int Status => status; }

dotnet run

not found
server error
other 301
done

Three errors of one type went to three blocks, and the last one is the fallback with no filter. Without it, a 301 would have left the method unhandled, which is the honest default: a filter that matches nothing is not a catch-all.

Rules of a filter

Exercises

  1. Add a filter on e.Message.Length > 10 to the first program and call Fail with a long reason.
  2. Make Log return true and see which line prints instead of the outer catch.
  3. Add a fourth HttpError case for status >= 400 && status < 500.
  4. Throw from inside the filter and explain why the program still ends in the outer catch.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. When does the block of catch (T e) when (cond) run?

    Answer

    When the exception is a T and cond is true

    The type is checked first, then the filter decides whether this block handles it.

  2. What happens when a filter returns false?

    Answer

    The next catch is tried, as if the type had not matched

    A false filter declines the exception, and the search continues.

  3. What does this program print? try { throw new Exception("x"); } catch (Exception e) when (e.Message == "y") { Console.WriteLine("y"); } catch (Exception e) when (e.Message == "x") { Console.WriteLine("x"); }

    Answer

    x

    The first filter is false, so the second one handles the exception.

  4. Why is a filter that logs and returns false useful?

    Answer

    It records the error without taking responsibility for it

    The exception continues to the real handler with its original trace intact.

  5. What may a when clause not contain?

    Answer

    await

    A filter is synchronous, so an await is not allowed in it.

  6. What does this program print? try { throw new Exception("abc"); } catch (Exception e) when (e.Message.Length > 5) { Console.WriteLine("long"); } catch (Exception) { Console.WriteLine("short"); }

    Answer

    short

    The message has three characters, so the first filter declines and the fallback runs.

  7. When does the runtime evaluate a filter?

    Answer

    Before the stack is unwound

    That is why the trace is untouched and the frames below still exist.

  8. What happens if the filter itself throws?

    Answer

    The filter counts as false and the original exception continues

    The runtime swallows the filter exception so the original error is not lost.

  9. What does this program print? try { throw new InvalidOperationException(); } catch (InvalidOperationException) { Console.WriteLine("one"); } catch (InvalidOperationException) { Console.WriteLine("two"); }

    Answer

    the build fails: the second catch is unreachable

    CS0160 rejects a second catch of the same type with no filter to tell them apart.

  10. Which catch handles an exception that no filter matched?

    Answer

    A catch of the same type with no filter, if there is one

    Without a matching filter or a plain catch, the exception leaves the method.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev