Fix S2737 FP: Catch clause with when shouldn't warn
Closed this issue · 1 comments
linkdotnet commented
Description
S2737 indicating: ""catch" clauses should do more than rethrow" also triggers in combination with when
clauses.
Repro steps
A simple example could be modelled as such:
using var tokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, anotherToken);
try
{
await MyAsyncOperation(tokenSource.Token);
}
catch (OperationCanceledException e) when (e.CancellationToken == token)
{
throw;
}
Expected behavior
In this case I'd argue it is not the same as a catch-all clause that rethrows.
Actual behavior
A warning is issued.
Known workarounds
Of course there is the possibility to add the when
clause as if
filter inside the catch-block.
Related information
- C#/VB.NET Plugins version:
- Visual Studio version: -
- MSBuild / dotnet version: 8.0
- SonarScanner for .NET version (if used): 9.25.0.90414
- Operating System: MacOS 14.5
Tim-Pohlmann commented
This exception covers this case:
This rule will not generate issues for catch blocks if they are followed by a catch block for a more general exception type that does more than just rethrowing the exception.
If you don't add a more general catch clause, the catch (...) when ...
is superfluous.
using var tokenSource = CancellationTokenSource.CreateLinkedTokenSource(token, anotherToken);
try
{
await MyAsyncOperation(tokenSource.Token);
}
catch (OperationCanceledException e) when (e.CancellationToken == token) // Compliant
{
throw;
}
catch
{
// do something else than just throw (or do nothing)
}