Short answer
Yes – it’s perfectly fine (and often desirable) to catch an OperationCanceledException, log it, and then re‑throw it with throw; so the caller sees the original exception and its stack trace.
You only need to do this if you have something to do before the exception leaves the method (e.g., logging, releasing a resource that isn’t covered by a finally, or translating the exception into a domain‑specific one).
If you have nothing to do, just let the exception bubble up – there’s no need to add a catch block at all.
Below is a deeper dive into the why, the when, and a few practical refinements you can apply to the pattern you posted.
1. Why catching and re‑throwing can be useful
| Reason | What you gain | What you lose (if you don’t) |
|---|
| Logging | You get a record of the cancellation (useful for diagnostics, especially in production) | No log entry – you may have to rely on higher‑level logs that may not include the exact call site |
Cleanup that isn’t in a finally | You can run async cleanup code that must happen only on cancellation (e.g., abort a pending request, release a semaphore) | Cleanup may be missed or have to be duplicated elsewhere |
| Exception translation | You can wrap the cancellation in a domain‑specific exception (rare, but sometimes required) | Callers will only see the raw OperationCanceledException |
| Adding context | You can add extra data to the log (e.g., which operation was cancelled, which endpoint) | No contextual information in the logs |
If none of the above apply, the simplest and most performant thing is to omit the catch entirely and let the exception propagate automatically.
2. How to do it right
2.1 Preserve the original stack trace
catch (OperationCanceledException)
{
logger.LogInformation(ex, "Write operation canceled for endpoint {Endpoint}.", dnsEndPoint);
throw; // <-- NOT `throw ex;`
}
throw; re‑throws the original exception, preserving its stack trace. throw ex; would reset the stack trace, making debugging harder.
2.2 Log at the appropriate level
Cancellation is usually an expected flow, not an error. Most teams log it at Information or Debug level, not Warning:
logger.LogDebug(ex, "Write operation was cancelled by the caller.");
If you treat cancellation as an abnormal situation in your domain (e.g., a user‑initiated abort that should be highlighted), Warning can be justified, but be consistent.
2.3 Verify the token (optional but nice)
If your method receives multiple tokens (e.g., a linked token), you might want to make sure the exception really came from the token you passed in:
catch (OperationCanceledException ex) when (ex.CancellationToken == cancellationToken)
{
logger.LogDebug(ex, "Write operation cancelled by the caller's token.");
throw;
}
If the exception came from a different token (perhaps an internal timeout token you created), you can handle it differently or let it bubble up.
2.4 Use exception filters instead of a full catch block (C# 6+)
If you only need to log and you don’t need any await or other async work in the handler, an exception filter keeps the stack trace intact and avoids the extra catch scope:
try
{
await EnsureConnectedAsync(cancellationToken).ConfigureAwait(false);
await _stream!.WriteAsync(data, 0, data.Length, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException ex) when (LogCancellation(ex))
{
// The filter already logged; just re‑throw.
throw;
}
// Helper used in the filter
static bool LogCancellation(OperationCanceledException ex)
{
logger.LogDebug(ex, "Write operation cancelled.");
return true; // let the catch block execute (which just re‑throws)
}
Because the filter runs before the stack trace is captured, the throw; that follows still preserves the original stack trace.
2.5 Keep the “other‑exception” path clean
Your existing catch (Exception) block does a good job of:
- Logging the failure,
- Cleaning up the connection,
- Wrapping the original exception in a domain‑specific one.
A couple of minor tweaks:
- Prefer
await using for the stream if you ever need to dispose it on failure.
- Avoid swallowing the original exception’s stack trace – you already preserve it by passing it as the inner exception, which is great.
catch (Exception ex) when (!(ex is OperationCanceledException))
{
logger.LogError(ex, "Write operation failed; cleaning up connection.");
await CloseAndCleanupConnectionAsync().ConfigureAwait(false);
throw new TcpConnectionFailedException(
$"Failed to write to {dnsEndPoint}.", ex);
}
The when clause makes it explicit that we don’t want to handle OperationCanceledException here.
3. Putting it all together – a polished version
public async Task WriteDataAsync(byte[] data, CancellationToken cancellationToken)
{
try
{
await EnsureConnectedAsync(cancellationToken).ConfigureAwait(false);
// _stream is guaranteed non‑null by EnsureConnectedAsync.
await _stream!.WriteAsync(data, 0, data.Length, cancellationToken)
.ConfigureAwait(false);
}
// 1️⃣ Log and re‑throw cancellation (expected flow)
catch (OperationCanceledException ex) when (ex.CancellationToken == cancellationToken)
{
logger.LogDebug(ex, "Write operation cancelled by caller for endpoint {Endpoint}.", dnsEndPoint);
throw; // preserve original stack trace
}
// 2️⃣ Handle any *other* failure
catch (Exception ex) when (!(ex is OperationCanceledException))
{
logger.LogError(ex, "Write operation failed; cleaning up connection to {Endpoint}.", dnsEndPoint);
await CloseAndCleanupConnectionAsync().ConfigureAwait(false);
throw new TcpConnectionFailedException(
$"Failed to write to {dnsEndPoint}.", ex);
}
}
What changed?
| Change | Reason |
|---|
catch (OperationCanceledException ex) when (ex.CancellationToken == cancellationToken) | Guarantees we only treat our token’s cancellation as “expected”. |
LogDebug instead of LogWarning | Cancellation is usually not a warning. |
throw; (not throw ex;) | Preserves the original stack trace. |
catch (Exception ex) when (!(ex is OperationCanceledException)) | Makes it crystal‑clear we’re not handling cancellation here. |
| Added endpoint information to log messages | Gives you context without having to dig into the stack trace. |
4. TL;DR checklist for your method
-
Do you need to do anything on cancellation?
- ✅ Yes →
catch (OperationCanceledException) (or filter) → log → throw;
- ❌ No → remove the catch; let it bubble.
-
Are you logging at the right level?
- Use
Debug/Information for expected cancellations.
- Use
Warning/Error only if cancellation truly indicates a problem in your domain.
-
Are you preserving the stack trace?
- Always re‑throw with
throw;, never throw ex;.
-
Do you need to differentiate tokens?
- Use an exception filter (
when (ex.CancellationToken == cancellationToken)) if you have multiple tokens.
-
Is there any other cleanup needed?
- If you have async cleanup that should run only on cancellation, do it inside the
catch before re‑throwing.
Bottom line
Catching OperationCanceledException just to log and re‑throw is a perfectly logical pattern when the cancellation token originates from the caller. It gives you visibility into a normal control‑flow event without altering the exception semantics. If you have no extra work to do, you can safely omit the catch and let the exception propagate automatically. Either way, make sure you preserve the original stack trace and log at an appropriate level.