2

I have a Java code as follows

try {
    while (true) {
        // do something without break but will throw an expected
        // exception in some random iteration of the loop
    }
} catch (Exception e) {
    // handled properly
}

This is reported by Sonar to be a Blocker Bug, description as mentioned here. How can I get rid of this as I am actually expecting my loop to be ended by an exception and hence no break is required.

Mukund Jalan
  • 1,145
  • 20
  • 39
  • You can use the SuppressFBWarnings Annotation like https://stackoverflow.com/questions/10971968/turning-sonar-off-for-certain-code. But looks like you should think over your solution – Jens Feb 02 '18 at 06:35
  • 1
    The rule does not support exceptions well, read this: [SONARJAVA-1944](https://jira.sonarsource.com/browse/SONARJAVA-1944) – agabrys Feb 02 '18 at 19:38

1 Answers1

3

Using exceptions for control flow is generally not considered good coding practice. Reasons for this can be found here.

If you still want this to work, you may be able to do this:

while(true) {
    try {
        //code...
    } catch (Exception e) {
        //code...
        break;            
    }
}

The break within the loop should make it work.

Joshua Perrett
  • 354
  • 4
  • 10
  • 1
    this is not working for me. I added an exception and an if, but it still gives that blocker. And I need to figure this out this is a thread for a clean up process (cleans some data up in the DB) that needs to run for the full time the application is running. – mpop Feb 08 '19 at 12:34
  • @mpop If you have an 'if' that might be the reason that sonar is still complaining, without the full example it is difficult to tell why Sonar is complaining. – Mukund Jalan Jan 04 '20 at 13:15