S1854 C# False positive in loop with try/catch block

In the code below, a false positive is reported in the “while” line regarding ‘numberOfTries’.
It does not take into account that the line ‘Int.Parse…’ could throw an exception, in which case the break will not be executed. The ‘Int.Parse’ is only an example and can be replaced by any other code that potentially throws an exception.

var path = @"C:\foo.txt";
int result = 0;

int numberOfTries = 0;
while( numberOfTries++ < 20 )
          result = int.Parse( File.ReadAllText( path ) );
          System.Threading.Thread.Sleep( 200 );

Hey there.

Thanks for the report. It looks like you’re facing an existing false-positive you can track here: Fix S1854 FPs: Improve catch block links · Issue #4949 · SonarSource/sonar-dotnet · GitHub

You’re right. I searched for S1854 before filing my issue but I missed this one.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.