Chapter 5: Error handling and resource management
Writing code that runs is not hard. Writing robust code that doesn’t crash unexpectedly requires a solid understanding of error handling and resource management. In the .NET world, exceptions are the standard mechanism for handling errors, while the IDisposable interface is the core of resource management.
Developers often stumble over the following aspects of these two topics:
- Error handling: Errors can be expressed through exceptions or return values. How can you tell callers what went wrong and what to do next?
- Resource management: Forgetting to release resources can cause memory leaks, file locks, and exhausted database connections. How do you ensure resources are always released, even when exceptions occur?
- Asynchronous disposal: Some resources require I/O during cleanup, such as flushing buffered data to a file.
DisposeAsynccan avoid blocking the thread while waiting; useDisposewhen cleanup does not need asynchronous waiting.
This chapter follows two main threads: how to represent and propagate errors when something goes wrong, and how to release resources reliably after you are done with them. We will cover:
- Golden rules and common anti-patterns for exception handling
- When to use
try-catch-finally usingstatements and theIDisposablepattern- Async resource management (
IAsyncDisposableandawait using) - Resource ownership, simple and inheritable Dispose patterns, and when a finalizer is needed
Once you understand these practices, you will have a clearer sense of which failures should become exceptions, which ones are better expressed as return values, and which resources need explicit cleanup.
5.1 Exception handling
Exception handling isn’t just about wrapping code in try-catch blocks. When used correctly, it improves both debugging and maintainability. When used poorly, it can degrade performance and mask the root cause of a problem.
C# uses structured exception handling, which separates error-handling logic from the normal flow. This also raises common questions:
- When should you throw exceptions? If user input is invalid, should you throw or return a value?
- How should you catch exceptions? What is wrong with
catch (Exception)? - How should you rethrow exceptions? What happens if you use
throw ex;? - How do you guarantee resource cleanup? Even when exceptions occur, you still need to close files and connections.
We will start with exception handling and look at several choices that directly affect readability and debugging:
- Distinguishing exceptions from normal control flow (Section 5.3 compares Tester-Doer and Try-Parse)
- Catch specific exceptions instead of generic ones
- Use exception filters (
when) to improve debugging - Concise
throwexpressions - Rethrow correctly (preserve stack traces)
- Use
finallyto ensure resource cleanup
.NET 9 performance improvements
.NET 9 introduced a new exception handling implementation based on NativeAOT, improving performance by 2x to 4x. Even when exceptions must be used, their performance overhead is noticeably smaller than before. Still, for expected errors (like user input), you should prefer
TryParseand similar patterns.
Exceptions are only for exceptional cases
Here is a typical pattern: wrap the normal flow in a try block and handle exceptions in catch:
You can read this as: “try to run some code and see if anything goes wrong. If something unexpected happens, stop the normal flow and pass the captured exception to the catch block to handle it.”
Exceptions are useful when a method cannot complete its intended work and needs to communicate the failure to a caller that can handle it. For example, a missing required configuration file usually interrupts the operation. But if failure is an ordinary result, such as user input that may not convert to an integer, returning success or failure may be more natural. Section 5.3 compares these designs with Parse and TryParse.
Catch specific exceptions
Avoid catching everything (catch (Exception ex)) unless you have a clear responsibility, such as logging errors at the application boundary or isolating failures of individual jobs. An intermediate layer that catches everything may swallow programming bugs or errors the caller could handle, making the real problem harder to trace. Catching specific exceptions lets you respond precisely to different errors.
There are several ways to write catch clauses:
// Catch a specific exception and access the exception object
catch (FileNotFoundException ex)
{
Console.WriteLine(ex.Message);
}
// Only care about the type, no exception variable needed
catch (IOException)
{
// Handle I/O errors
}
// Catch all exceptions (usually only at the outermost layer)
catch
{
// Exceptions not handled by earlier catch clauses end up here
}When you catch specific exceptions, you can provide tailored responses—like distinguishing between a missing file and a permission error—rather than a vague “something went wrong” message. This makes your application’s behavior more predictable and user-friendly.
Exception filters
Suppose a method calls an HTTP API and can handle only a 404 (resource not found) response. Other HTTP failures should be passed to the caller. The older approach catches the exception first, then checks the status code:
Starting with C# 6, when lets you put the condition directly on the catch clause:
Both approaches handle only 404; other HTTP errors propagate. The difference is that the when condition is evaluated before stack unwinding. If it is false, the runtime continues looking for another handler without first entering a catch and rethrowing. This makes the condition clearer and preserves the call stack and local state while the filter is evaluated, which helps when debugging. Keep filter conditions simple and avoid actions that modify program state.
Rethrow correctly
If you need to rethrow an exception from a catch block, always use throw; instead of throw ex;.
The detail is easy to miss: throw ex is legal C#, but it changes the stack information stored on the exception. The difference is:
throw: Preserves the original stack trace, so you can still locate where the exception first happened.throw ex: Resets the stack trace. The caller cannot see the original location in the exception’sStackTrace. If you need to present a higher-level error to the caller, wrap the original exception and keep it inInnerExceptioninstead of destroying the original stack trace withthrow ex.

Call stack and stack trace
A stack trace is a string that lists every method in the current call stack and the line number of each method (if debug symbols are available).
A call stack is a memory structure that stores the sequence of method calls for a thread, including parameters and local variables.
Throw expressions
Starting with C# 7, throw can be used as an expression, not just as a statement. This lets you throw in more contexts:
// In expression-bodied members
public string GetName() => throw new NotImplementedException();
// In a ternary operator
string ValidateInput(string? input) =>
input != null ? input.Trim() :
throw new ArgumentNullException(nameof(input));
// In the null-coalescing operator
string result = userInput ??
throw new ArgumentNullException(nameof(userInput));Source code: DemoThrowExpressions
The common idea in these examples is that an exception no longer has to appear only as a standalone throw statement. It can live where a value is expected. For checks where “no value” means execution should not continue, this keeps the failure condition close to the value being used.
ArgumentNullException.ThrowIfNull (.NET 6+)
The previous section showed throw expressions combined with ?? to validate null parameters. Starting with .NET 6, there is an even more concise dedicated method:
This ThrowIfNull helper not only makes the code shorter, but also carries the parameter name into the exception object even when you do not write nameof(data) yourself; the compiler supplies the argument name at the call site.
For example, when data is null, ArgumentNullException.ThrowIfNull(data) still knows that the problematic parameter name is data, which makes the error message clearer.
Later .NET versions added more helpers. Relevant docs:
- ArgumentException.ThrowIfNullOrEmpty: Throw if the string is
nullor empty. - ArgumentException.ThrowIfNullOrWhiteSpace: Throw if the string is
nullor whitespace.
Numeric parameters have similar helpers. For example, ArgumentOutOfRangeException.ThrowIfNegative(quantity) rejects negative quantities and supplies the parameter name automatically. See the ArgumentOutOfRangeException API documentation for other checks.
Wrap exceptions and preserve inner exceptions
Sometimes you want to throw a different exception type, such as translating low-level details into a higher-level message. In that case, keep the original exception as the InnerException property of the new one:
This way, different failures stay clearly separated: a null argument results in ArgumentNullException, while a malformed date string is wrapped as a higher-level ArgumentException. The caller gets an API-friendly error message, can identify the offending parameter through ParamName, and can still inspect the low-level cause (FormatException) via InnerException.
Key properties of Exception
Knowing where an exception came from and why it happened is usually more useful than merely knowing that something failed. System.Exception is the base class for all exceptions, and the following example shows the properties you will use most often while debugging:
try
{
// Code that may throw
}
catch (Exception ex)
{
// Message: short error description
Console.WriteLine($"Message: {ex.Message}");
// StackTrace: full call stack showing the exception path
Console.WriteLine($"Stack trace: {ex.StackTrace}");
// InnerException: wrapped inner exception (if any)
if (ex.InnerException != null)
{
Console.WriteLine(
$"Inner exception: {ex.InnerException.Message}");
}
}When reading exception details, start with Message to understand the surface error, then use StackTrace to find where it occurred. If the exception has been wrapped, InnerException is often the clue closest to the root cause.
Exception inheritance hierarchy
All C# exception types derive from System.Exception. Many built-in exceptions derive from SystemException, but when choosing a catch clause, focus on the error represented by the specific type: ArgumentException indicates an invalid argument, and IOException indicates an I/O failure. Custom exceptions typically derive directly from Exception; there is no need to inherit from the older ApplicationException.
Additional background: arithmetic overflow
Integer operations at run time normally do not check for overflow by default. Use
checkedif overflow should throwOverflowException. Constant expressions at compile time check for overflow by default unless you explicitly useunchecked.
finally clause: ensure resource cleanup
When control leaves a try block normally or the stack unwinds because of an exception, the finally block normally runs. This makes it a good place for cleanup:
StreamReader? reader = null;
try
{
reader = new StreamReader("app.config");
var content = reader.ReadToEnd();
Console.WriteLine(content);
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"File not found: {ex.Message}");
}
finally
{
// Cleanup on normal exit or during stack unwinding
reader?.Dispose();
}Here is how it works:
- If a line inside try throws, the remaining code is skipped. Control moves to a matching catch, if one exists, and then finally runs.
- Even when no catch clause handles the exception locally, finally runs as the stack unwinds before the exception propagates outward. This does not guarantee cleanup if the application is forcibly terminated before reaching finally.
Source code: DemoExceptionHandling
5.2 Resource management
The GC reclaims memory occupied by managed objects that are no longer referenced, but resources such as file handles and database connections generally cannot wait for the GC. Even when wrapped in a managed object, a resource should be disposed of when the work is done.

This section starts with using, then discusses who is responsible for disposal and when your own classes should implement IDisposable.
Automatic cleanup with using
Section 5.1 used try-finally to close a StreamReader. Since this pattern is common, C# provides the using statement, which lets the compiler arrange for Dispose to be called when the block is exited.
The block defines the scope in which the resource is used. Even if ReadToEnd throws, Dispose is called during normal stack unwinding.
using declaration (C# 8)
C# 8 introduced the using declaration, so each resource no longer needs its own pair of braces. Here is the same file-reading example:
If you only need the resource for part of a method, a conventional using block or a smaller scope can release it sooner. When you need it until the method ends, a using declaration is usually more concise.
Resource ownership
When designing APIs, a more important question than which using syntax to choose is who is responsible for releasing the resource? This is resource ownership.
By default, a StreamReader closes the stream passed to it when it is disposed. If the outer scope needs to continue using the stream, specify leaveOpen: true so that the outer scope retains ownership:
Here the outer scope creates and disposes file, and reader only borrows it. Multiple using declarations are disposed in reverse declaration order, so reader, which depends on file, is cleaned up first. If all you need is to read text, creating a StreamReader directly from a file path is sufficient; you do not need to manage a separate FileStream.
In general, the code that creates a resource is responsible for disposing it unless the API explicitly transfers ownership. When accepting an externally supplied resource, check the contract rather than disposing it unconditionally.
Both resources in the diagram are managed by the outer scope; reader only borrows file.
Async disposal
The using syntax shown so far releases resources synchronously. However, with async programming, resource cleanup can also be I/O-bound (such as closing a stream or database connection). To handle these scenarios, C# 8 introduced the IAsyncDisposable interface and await using. Here is an example:
The key point in this code is that when execution leaves the scope, the compiler arranges to call DisposeAsync instead of the synchronous Dispose. If you are designing a type that performs asynchronous cleanup, implement IAsyncDisposable and let callers release it with await using.
Source code: DemoUsingStatements
Pay close attention to one detail: if you wrap an await using resource inside another wrapper that only implements IDisposable (for example, a StreamReader created with its default constructor), that wrapper may close the underlying resource synchronously first, because by default it also disposes the stream it wraps.
If you truly want the underlying FileStream to go through DisposeAsync, keep the wrapper from closing the inner stream (for example, by using leaveOpen: true), or apply await using directly to the underlying resource.
Why DisposeAsync?
With
FileStream, closing the file may need to flush buffered data to disk. If you useDispose, the flush is synchronous and can block, especially on network drives.DisposeAsynclets resources that support asynchronous I/O wait for cleanup without continuously occupying the calling thread; the actual benefit depends on the resource implementation and I/O conditions.Note
For more on
await usingandIAsyncDisposable, see Chapter 12, “Async Programming,” in the section on asynchronous disposal.
Implementing a simple IDisposable class
Suppose we design a class for reading text files and have it create its own StreamReader. Because it owns that resource, it needs to provide a way to release it:
public sealed class TextFileReader : IDisposable
{
private StreamReader? _reader;
public TextFileReader(string path)
{
_reader = new StreamReader(path);
}
public string ReadAll()
{
var reader = _reader
?? throw new ObjectDisposedException(nameof(TextFileReader));
return reader.ReadToEnd();
}
public void Dispose()
{
var reader = _reader;
_reader = null;
reader?.Dispose();
}
}Callers do not need to know how the StreamReader is managed internally. They can simply use using:
TextFileReader is a sealed class that owns only a managed object already implementing IDisposable. It needs neither a finalizer nor a virtual Dispose method. Setting the field to null prevents subsequent Dispose calls from disposing the same reader again; ReadAll rejects use after disposal. This example assumes single-threaded use. If cleanup fails, the exception propagates to the caller without an automatic retry.
Standard Dispose pattern (with finalizer support)
If a class permits inheritance, derived classes may have resources of their own to clean up. Provide a public Dispose method and an overridable Dispose(bool disposing):
public class ResourceHolder : IDisposable
{
private StreamReader? _reader;
public ResourceHolder(string path)
{
_reader = new StreamReader(path);
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
var reader = _reader;
_reader = null;
reader?.Dispose();
}
}
}A derived class can override Dispose(bool), clean up its own resources first, and then call the base implementation. If cleanup may throw, use try-finally to give the base class a chance to clean up. Public Dispose need not be virtual. GC.SuppressFinalize(this) prevents the object’s finalizer from running after successful disposal, including a finalizer defined by a derived class.
The class above has no finalizer, so disposing is true in ordinary use. The false path is reserved for types with a finalizer. Owning managed IDisposable objects alone does not require adding a finalizer.
Finalizer: the last line of defense
If a class directly owns unmanaged resources, such as memory or handles allocated by a native API, the GC does not know how to release them. Prefer wrapping these resources in SafeHandle, which handles finalization if necessary. The owning class then only needs to dispose of the SafeHandle.
Consider defining a finalizer yourself only when you really must manage unmanaged resources directly without a reliable wrapper such as SafeHandle. The following illustrates the call path only; it is not a complete unmanaged-resource implementation:
In this pattern, Dispose(true) cleans up managed and unmanaged resources, while Dispose(false) cleans up only the unmanaged resources the object directly owns, without relying on the state of other managed objects. The implementation must also prevent double release and handle partially completed construction. Finalizer timing and order are unpredictable, and a finalizer is not guaranteed to run before the process exits. It cannot replace explicit disposal.
A finalizer should not perform I/O, logging, or other work that might block or throw. Finalization also increases GC overhead. See Microsoft’s Implement a Dispose method for the complete pattern for owning native resources.

Source code: DemoDisposePattern
The example project includes a sealed class that actually owns a StreamReader, an inheritable Dispose pattern, and an illustration of the finalizer path. Its handle is only a simulated value; it does not call native APIs.
Anonymous disposal
IDisposable is useful not only for releasing files or connections but also for wrapping cleanup that needs to run on leaving a scope, such as restoring event notifications after temporarily suspending them. This is called anonymous disposal. It involves delegates and lambdas from Chapter 8, so the full example appears in Section 9.6, Anonymous disposal.
Source code: DemoAnonymousDisposal (Read Chapter 9 before running this example.)
5.3 Exceptions vs. error codes: when to use which
Not all errors should be handled with exceptions. When designing APIs, consider the caller’s needs.
We have already mentioned several times that an expected failure is not always a good fit for exceptions. Here is the decision point more explicitly: when should you throw exceptions, and when should you return an error code (or a boolean)? Poor choices lead to:
- Overusing exceptions: Worse performance, confusing control flow, and forcing callers to handle expected failures as “exceptions”
- Overusing error codes: Callers may forget to check errors, handling becomes scattered, and root causes become harder to track.
This section uses two common .NET patterns as a guide:
- Tester-Doer and Try-Parse patterns: how .NET avoids turning expected failures into exceptions
- API design considerations: when to throw vs. when to return error codes
- Practical guidance: when to provide a
TryXxxmethod
Tester-Doer and Try-Parse patterns
The .NET class library commonly offers both patterns, but they are not the same design.
In the Tester-Doer pattern, one member checks a condition and another performs the operation, such as IsReadOnly and Add. If failure is common, callers can check first and decide whether to proceed. However, state may change between the two steps: even after File.Exists returns true, the file may be deleted. A preliminary check does not guarantee success; you still need to handle actual exceptions.
Another common design is the Try-Parse pattern:
// Parse: input is expected to be valid; failure throws
int result = int.Parse(input); // May throw FormatException or OverflowException
// TryParse: input may be invalid; failure returns false
if (int.TryParse(input, out int parsed))
{
Console.WriteLine($"Converted successfully: {parsed}");
}
else
{
Console.WriteLine("Input format is invalid. Please try again.");
}Putting these two patterns side by side gives us this rule of thumb:
- Use Tester-Doer when the API already provides an inexpensive and explicit way to check whether an operation should be attempted.
- Use
Parsewhen the method contract requires valid input and failure should interrupt the operation while retaining exception information (not necessarily because of a programming bug). - Use
TryParsewhen input comes from users or external systems and failure is expected.
Compared to throwing exceptions, TryParse is a good fit when failure is a normal result and the caller will branch based on success or failure. Tester-Doer fits when the API can provide a cheap, explicit check before the caller attempts the operation.
Designing your own APIs
When designing methods, use these principles:
- Throw exceptions when a precondition is violated or a method cannot fulfill its contract and the caller needs details such as the cause and stack trace. Even a foreseeable failure may warrant an exception.
- Return a result when failure is an ordinary outcome and callers usually branch on the result. If they need more than success or failure, define a result type that includes the reason; you need not return only a boolean or number.
Practical advice
If failure is common and expected, and callers usually only need a success/failure result (for example parsing, dictionary lookup, or input validation), consider offering a
TryXxxversion. For file or network operations, where the reason for failure often matters, exceptions are still usually the better design because callers often need details such as a path, status code, or underlying cause.
Summary
- Exceptions and return values: Choose based on the method contract, failure frequency, and information callers need. Consider
TryXxxfor common, ordinary failures. - Exception filters: Use
whento catch only what you need. - Preserve stack traces: Use
throw;instead ofthrow ex;. - Wrap exceptions: Pass the original exception to the new one as
InnerException. - finally and cleanup:
finallynormally runs when control leaves the try block, including during stack unwinding, but is not guaranteed on forced process termination. - Using declarations: Use C# 8
using varto reduce nesting; use a smaller scope when you need earlier cleanup. - Resource ownership: Identify who is responsible for cleanup. A sealed class owning only IDisposable resources can implement Dispose directly; consider finalization only for directly owned unmanaged resources, and prefer SafeHandle.
- Async cleanup: Use
IAsyncDisposableandawait usingfor cleanup that requires I/O. - TryXxx pattern: Offer
TryXxxmethods for expected failures.
Glossary
| Term | Description |
|---|---|
| Anonymous disposal | Pattern that creates a short-lived IDisposable via delegates |
| Dispose | Explicitly release resources, typically via IDisposable |
| Exception | An error or abnormal condition during program execution |
| Exception filter | Use when conditions to decide whether to catch an exception |
| Finalizer | Nondeterministic fallback cleanup managed by the GC, syntax ~ClassName() |
| Resource ownership | Contract determining which object or caller is responsible for releasing a resource |
| Inner exception | The original exception that caused the current one, stored in InnerException |
| Managed resource | Resources managed by the CLR, such as objects in memory |
| Stack trace | Shows the call stack when an exception occurs |
| Stack unwinding | Leaving call frames and running associated cleanup as an exception propagates |
| Suppress finalize | Use GC.SuppressFinalize to prevent finalizer execution |
| Tester-Doer pattern | Test whether an operation can succeed before doing it |
| Throw expression | C# 7 feature: use throw in expressions |
| Unmanaged resource | Resources not managed by the CLR, like file or window handles |
| Using declaration | C# 8 syntax that auto-disposes without braces |