Logo
  • Home
  • Services
  • Articles
    • Local Notion

      Own your data with Local Notion

      →

    • BlockchainSQL Server

      Access Bitcoin as an SQL Database

      →

    • Auto Mouse

      Use your mouse pain-free

      →

    • 🌗

      Lumina

      Your display. Your way.

      →
    • Our Tech
    • Case Studies
    • Contact Us

Handle related exceptions with a C# exception filter

  1. Articles
  2. Coding
  3. .NET
  4. Handle related exceptions with a C# exception filter

Use an exception filter when several exception types need the same recovery action. A catch (Exception ex) when (...) clause can accept a narrow set of failures without swallowing everything derived from Exception. C# pattern matching makes the accepted set readable.

The important decision is what recovery means. An input screen can reject a malformed number and let the user correct it. A service that cannot complete an operation should usually propagate the failure to an appropriate boundary. Catching an exception does not by itself make continued execution correct.

Run a narrow filter

Create a .NET 10 console application with dotnet new console -n FilterDemo -f net10.0. Replace Program.cs and run dotnet run --project FilterDemo from the parent directory.

C#
using System;
using System.Globalization;

foreach (var input in new[] { "42", "not-a-number", "2147483648" }) {
	try {
		var value = int.Parse(input, CultureInfo.InvariantCulture);
		Console.WriteLine($"Accepted {value}");
	} catch (Exception ex) when (ex is FormatException or OverflowException) {
		Console.WriteLine($"Rejected {input} ({ex.GetType().Name})");
	}
}

try {
	ParseAndReport(null);
} catch (ArgumentNullException) {
	Console.WriteLine("Null propagated to the outer boundary");
}

static int ParseAndReport(string? text) {
	try {
		return int.Parse(text!, CultureInfo.InvariantCulture);
	} catch (Exception ex) when (ex is FormatException or OverflowException) {
		Console.WriteLine("Expected parsing failure");
		throw;
	}
}

Expected output:

Plain text
Accepted 42
Rejected not-a-number (FormatException)
Rejected 2147483648 (OverflowException)
Null propagated to the outer boundary

The last call deliberately supplies null to demonstrate a failure outside the filter. The null-forgiving operator suppresses a compiler warning for that specific demonstration. It performs no runtime check. Normal production code should state whether null is allowed and validate it explicitly.

Keep recovery and diagnostics separate

FormatException and OverflowException share the input-rejection branch. ArgumentNullException does not match, so the search for a handler continues. An application defect such as a missing required dependency should not accidentally become an ordinary validation result.

If different exceptions need different actions, use separate catch clauses. Put more specific exception types before broad base types. A network timeout, an authentication failure and malformed JSON may all occur in one request, but they do not necessarily deserve the same retry, message or response code.

When a handler adds useful context and then rethrows, use throw;. It preserves the original exception stack. Writing throw ex; updates that stack and can obscure the original failure site. Creating a new domain exception is appropriate when translating an abstraction boundary, but retain the original exception as InnerException.

Keep the filter simple

Filters are evaluated before stack unwinding. Avoid mutating application state inside them. A type test or a stable error-code comparison is easier to reason about than a filter that performs I/O, changes a transaction or throws another exception. Put recovery work in the catch body.

Prefer TryParse for routine numeric validation where invalid input is expected frequently. This example uses Parse to make exception selection observable. A filter remains useful when calling an API whose contract reports the expected failures with exceptions and no suitable nonthrowing alternative exists.

Finally, keep the protected operation small enough that the filter has a clear meaning. A catch around an entire workflow can mistakenly classify an exception from an unrelated later step as an input error. Test both accepted exception types and at least one failure that must escape the handler.

References

Exception-handling statements - throw and try, catch, finally - C# reference
Use the C# throw statement to signal an occurrence of an exception. Use the C# try statements to catch and process exceptions occurred in a block of code.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/exception-handling-statements
Best practices for exceptions - .NET
Learn best practices for exceptions, such as using try/catch/finally, handling common conditions without exceptions, and using predefined .NET exception types.
https://learn.microsoft.com/en-us/dotnet/standard/exceptions/best-practices-for-exceptions
Int32.Parse Method (System)
Converts the string representation of a number to its 32-bit signed integer equivalent.
https://learn.microsoft.com/en-us/dotnet/api/system.int32.parse?view=net-10.0

Question provenance

This article addresses Catch multiple exceptions at once? , asked by Michael Stum on Stack Overflow. The source question is licensed under CC BY-SA 4.0 . The explanation and examples here are newly authored for current .NET. No answer text or code is reproduced.

Author: Herman Schoenfeld

COMPANY

Our Process

Case Studies

Our Technology

Contact Us

SERVICES

AI Engineering

Blockchain/Web3

Desktop Software Dev

App Development

Web Development

Enterprise Systems

IT Services

Consulting

PRODUCTS

BlockchainSQL Server

Local Notion

Notion CMS

Auto Mouse

LEGAL

Website Terms of Use

Privacy Policy (GDPR)