Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Exception Handling: Patterns for Robust Code

Practical C# exception handling patterns: try-catch-finally, exception filters, custom exceptions, performance tradeoffs, async code, and result types.

~6 min readC#
#Exception Handling#try-catch#Custom Exceptions#Exception Filters
Illustration of C# exception handling showing a try block with a catch block and an error icon.

Exception handling in C# requires understanding the core syntax, runtime behavior, and practical implementation patterns. In C#, exception handling is built around the try-catch-finally construct, but using it effectively means more than wrapping every method body in a try block. The language gives you several tools to control how exceptions flow through your code; choosing the right pattern affects reliability, readability, and runtime cost.

The Core Try-Catch-Finally Structure

The fundamental syntax is straightforward: a try block contains code that might throw, a catch block handles a specific exception type, and an optional finally block runs regardless of whether an exception occurred. The finally block is the right place for cleanup that must happen no matter what, such as closing a file handle or releasing a lock.

csharp
FileStream stream = null; try { stream = File.OpenRead("data.txt"); // Process the file } catch (IOException ex) { Console.WriteLine($"I/O error: {ex.Message}"); } finally { stream?.Dispose(); }

Here, the catch block only handles IOException. Any other exception type, such as UnauthorizedAccessException or ArgumentException, propagates up the call stack. The finally block guarantees that the stream is disposed even if an unexpected exception escapes. Keeping cleanup close to resource acquisition is preferable to relying on the caller to remember to dispose.

When to Catch and When to Let Exceptions Propagate

A common mistake is catching every exception at every layer. Catching an exception you cannot meaningfully handle obscures the original failure and makes debugging harder. Catch an exception when you can take a concrete recovery action, such as retrying an operation, providing a fallback value, or translating the exception into a more meaningful type for the caller.

If a method cannot do anything useful with an exception, let it propagate. For example, a data access layer might catch SqlException, log the failure, and rethrow a domain-specific RepositoryException, but it should not catch OutOfMemoryException or StackOverflowException because those indicate fatal conditions. Catching Exception broadly at the top of a request pipeline is acceptable for logging at an application boundary, but only if your code handles or rethrows it appropriately.

Using Exception Filters to Narrow Catch Blocks

C# 6.0 introduced exception filters, which let you specify a condition that must be true for a catch block to execute. This is more precise than catching a broad type and then checking a property inside the block, because the filter runs before the block is entered and does not catch the exception when the condition is false.

csharp
try { // Some operation that may throw } catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound) { // Only handle 404 responses } catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.ServiceUnavailable) { // Handle 503 with retry logic }

Filters keep related logic together and avoid the pattern of catching an exception, checking a condition, and rethrowing when it does not match. They also preserve the original stack trace because the exception is not caught and rethrown. When a filter evaluates to false, the runtime continues searching for a matching catch block. The StatusCode property on HttpRequestException is available in .NET 5+; if you target an earlier framework, filter on a property from your own exception type.

Designing Custom Exception Types

Creating a custom exception class is appropriate when you need to convey domain-specific error information that the built-in exception types do not capture. A well-designed custom exception should derive from Exception, provide constructors that are useful to callers, and expose additional properties that describe the error context.

csharp
public class OrderNotFoundException : Exception { public int OrderId { get; } public OrderNotFoundException(int orderId) : base($"Order {orderId} was not found.") { OrderId = orderId; } public OrderNotFoundException(int orderId, Exception innerException) : base($"Order {orderId} was not found.", innerException) { OrderId = orderId; } }

If the exception may cross process boundaries or be serialized, keep the serialization contract in mind. The historical pattern includes a protected serialization constructor, although modern .NET has moved away from binary serialization for exceptions. More importantly, do not create a custom exception for every possible failure; create one only when the exception type carries actionable information for the caller.

Performance Considerations

Exceptions are not free. Throwing an exception allocates an exception object, captures a stack trace, and unwinds the call stack. In hot paths where an error condition is expected and frequent, using exceptions for control flow can degrade performance. The runtime optimizes the common case where no exception is thrown, but the cost of throwing is high compared to a simple conditional check.

Consider a method that validates input and returns a result. Instead of throwing an exception for an invalid value, you might return a result object or use the Try pattern, as seen with int.TryParse. This is not about avoiding exceptions entirely; it is about reserving them for unexpected conditions.

Try/finally blocks are generally inexpensive when no exception is thrown, but they are still not the place for logic that does not need cleanup. Keep cleanup close to resource acquisition and avoid wrapping trivial code in try/finally just as a style habit.

Logging and Observability in Exception Handling

How you log exceptions is as important as how you catch them. When you log an exception, log the full exception object, not just ex.Message. The stack trace and inner exceptions contain the diagnostic context needed to trace the root cause. Use a structured logging framework that preserves exception properties, so you can query by exception type or message in your log aggregation tool.

csharp
try { // Operation } catch (Exception ex) { _logger.LogError(ex, "Failed to process order {OrderId}", orderId); }

In the catch block, avoid swallowing exceptions without logging. If you catch an exception and do not rethrow, you are deciding that the failure is non-fatal, and that decision should be visible in logs. Also be careful about logging at the correct level. A recoverable error might be Warning, while an unhandled exception that crashes the request is Error or Critical. Consistent levels make it easier to set up alerts and dashboards.

When an exception propagates across layer boundaries, consider adding contextual information. A common approach is to wrap the exception in a new exception that includes the original as an inner exception, preserving the stack trace while adding higher-level context such as the operation being performed or the user ID. Do not over-wrap; many nested exceptions make logs noisy and obscure the original failure.

Exception Handling in Asynchronous Code

Async and await introduce additional considerations. An exception thrown in an async method is captured and placed on the returned task. When you await that task, the exception is rethrown at the await point, so you can use try/catch around an await expression just as you would around synchronous code.

csharp
try { await _client.SendAsync(request); } catch (HttpRequestException ex) { // Handle network error }

A common pitfall is calling an async method without awaiting it and expecting exceptions to surface immediately. If you fire a task and never await it, the exception is stored in the task and will not be observed unless you await it or inspect the task's Exception property. Unobserved task exceptions can raise the TaskScheduler.UnobservedTaskException event, which is often ignored in modern .NET but still indicates a design flaw. Always await async calls or attach a continuation to handle failures.

Exception filters work in async code, but you cannot use an await expression inside the filter; the filter must be a synchronous boolean expression. If you need to asynchronously determine whether to handle an exception, catch it, perform the async check, and rethrow when the check fails.

Choosing Between Exceptions and Result Types

In applications with strict performance requirements or a functional style, developers often use result types instead of exceptions for expected failures. A result type, such as Result<T> or OneOf, makes the failure path explicit in the method signature and avoids the overhead of exception throwing. This approach is common in domain-driven design and in APIs where validation errors are part of normal flow.

The tradeoff is that result types require the caller to check for success or failure explicitly, which can lead to repetitive branching. Exceptions propagate automatically and can be caught at a higher level, reducing boilerplate for cross-cutting concerns like logging. There is no universal answer. Use exceptions for exceptional conditions the caller cannot reasonably anticipate, and use result types for expected, recoverable failures such as validation errors or business rule violations.

A hybrid approach is also viable: throw exceptions for programmer errors and unexpected runtime conditions, but return result types for domain validation. This keeps the exception path clean and makes expected failure modes visible in the code. If you choose result types, apply the approach consistently to avoid mixing paradigms in a way that confuses maintainers.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.