Variables that are only used in exception filters incorrectly trigger S1854
bool shouldCatch = false;
try
{
shouldCatch = true; //S1854 Remove this useless assignment to local variable 'shouldCatch'
throw new InvalidOperationException("bar");
}
catch (Exception) when(shouldCatch)
{
Console.WriteLine("Error");
}
S1854 should not trigger because the shouldCatch assignment is not useless. Indeed, without it the exception would pass through.
S1854 is triggered.
Hi @ohadschn.
Thanks for the feedback. This is going to be tricky to fix but we will see what we can do.
The issue is still there. Found a fix ?
My case :
public static void RetryOnException(int retries, TimeSpan delay, Action operation)
{
var attempts = 0;
do
{
try
{
attempts++; //Remove this useless assignment to local variable 'attempts'.
operation();
break;
}
catch (Exception ex)
{
if (attempts > retries)
throw;
Logger.LogError($"Exception caught on attempt {attempts} - will retry after delay {delay}", ex);
Task.Delay(delay).Wait();
}
} while (true);
}
This problem with the shape of the CFG may have some connection with #2393
Moving @killergege 's example to #2393 because it's a separate root cause (try-catch inside a loop vs try-catch with a throw inside the try, as in this original ticket problem), and we need to keep concerns separate between tickets.
Most helpful comment
The issue is still there. Found a fix ?
My case :