I'm using latest SonarQube server 9.4 and it constantly reports "Refactor this method to not always return the same value." - java:S3516 in piece of code like this:
try
{
FileUtils.moveFile(dcomExportFile, destination);
}
catch(IOException e)
{
Logger.error(this, "Could not move file {} to {}, future job runs might fail as well",
dcomExportFile.getAbsolutePath(), destination.getAbsolutePath());
return false;
}
return true;
Which is very strange because method FileUtils.moveFile can throw IOException and in this case method returns false.
Any idea?
Thx!
CodePudding user response:
I would move the return false
statement to outside and after the catch (where return true is now). And move the return true
to immediately follow the Fileutils call in the try block, like this:
try
{
FileUtils.moveFile(dcomExportFile, destination);
return true;
}
catch(IOException e)
{
Logger.error(this, "Could not move file {} to {}, future job runs might fail as well",
dcomExportFile.getAbsolutePath(), destination.getAbsolutePath());
}
return false;
It's confusing and arguably bad style to return from within a catch block anyway.
I'm not sure that in this case not letting the exception be thrown is a great idea because this seems like the sort of error I would want to bubble up, where having a return value lets it get lost too easily. Maybe it's not so bad if logging the error is the only thing the code does to handle this.
CodePudding user response:
I think it may not be good idea to just catch & log exception & return false
. You might need to throw exception back to caller of your method.
Good example which comes in my mind is list.add(..) where if operation is success it returns true
but in case of any failure it throws exceptions to caller instead of returning false
.
CodePudding user response:
I found solution - scanning with correct sonar.java.libraries path resolves this issue.