Trouble with try-catch-finally

Hi,

Since a couple of days, our company has introduced SonarQube on Android projects. Many issues have been solved already, except for one case: surrounding a FileOutputStream() object with try-catch-finally.

Before, the FileOutputStream() was not guarded with the try-catch-finally construction (note: we can’t use the try-with-rescources alternative since the API level used is 18 and should be 19+ for this alternative), so SonarQube/SonarLint was right in indicating it as a critical bug. Result: I guarded the construction as it should be guarded.

However, even if the guard is present and correctly implemented, SonarQube is still telling me to guard it like so:

Snapshot of code with issue underlined by SonarQube/SonarLint:

Oops… I wanted to post two more images but apparently new users can only post one image per post. Strange…

I will post the other 2 images in replies to this post, so pls. also check those.

I simply don’t understand as to why SonarQube/SonarLint still tells me to do something I already did…

Can someone shed a light on what else (if possible) has to be done?

Many thanks,

PS: I erroneously posted this very same topic on the wrong SonarQube forum. Apologise for that…

Best,
–Geert

1 Like

As promised, the second image showing a snapshot of the SonarQube/SonarLint tooltip:

Best,
–Geert

And here’s the third image I wanted to post on my first post: snapshot of SonarLint message regarding the issue I mentioned earlier:

Best,
–Geert

Hi Geert,

The flush() method throws IOException. If that happens, you won’t get to the close(), which is why you’re still getting an issue. So you can nest a try/catch inside your finally, or just use a try-with-resources (for far cleaner code).

Ann

2 Likes

Hi Ann,

Truly amazing hint and solution! Thanks very much for this prompt reply. I totally overlooked that one…

PS:
Unfortunately, I can’t use the try-with-resources in our project, since we’re still at API level 18 and try-with-resource is only possible from API 19+ onward. That would indeed be a far better and cleaner solution, fully agree…

Best rgds,
–Geert

1 Like