为什么sonar认为这个表达式总是错误的
在我的Java项目中,SonarQube说表达式总是假的。但是我不明白为什么。以下是相关代码:
BaseException baseException = null;
for (SpaceInfo i: spaceInfos) {
try {
processSingle(i.getSpaceKey(), i.getContentType());
} catch (BaseException e) {
baseException = BaseException.chain(baseException, e);
}
}
// Here sonar say that this condition will always evaluate to false.
if (baseException != null) {
throw baseException;
}
但是在我看来,如果processSingle
方法抛出一个BaseException
,那么baseException
不应该为null,因此表达式的计算结果不应该为false
processSingle方法声明如下:
private void processSingle(String spaceKey, String contentType) throws BaseException
当然,在某些情况下,processSingle
方法会抛出一个BaseException
。所以我认为声纳是错的。还是有什么我看不到的事情
更新:
这就是BaseException.chain()
所做的:
public static BaseException chain (BaseException a, BaseException b) {
if (a == null) { return b; }
a.setNextException(b);
return a;
}
这是processSingle
的代码:
private void processSingle(String spaceKey, String contentType) throws BaseException {
assert ContentTypes.Page.equals(contentType) || ContentTypes.BlogPost.equals(contentType);
Content content;
try {
content = createEmptyContent(spaceKey, contentType);
} catch (Exception e) {
throw new MessageToContentProcessorProcessSingleException(contentType, spaceKey, e);
}
BaseException baseException = null;
try {
contentCreator.addMetadata(content);
} catch (BaseException e) {
baseException = BaseException.chain(baseException, e);
}
Pair<List<AttachmentInfo>, FailedToSaveAttachmentException> pair = contentCreator.saveAttachments(messageParser.getContent(), content);
List<AttachmentInfo> attachments = pair.getLeft();
baseException = BaseException.chain(baseException, pair.getRight());
try {
String html = htmlGenerator.generateHtml(attachments, messageParser.getContent());
contentCreator.updateBodyOfContent(content, html);
} catch (BaseException e) {
baseException = BaseException.chain(baseException, e);
}
if (baseException != null) {
throw new MessageToContentProcessorProcessSingleException(contentType, spaceKey, baseException);
}
}
# 1 楼答案
为了测试/好奇,我会尝试:
这将显示Sonar是否认为可以抛出异常。或者如果它被
chain
方法或赋值语句(赋值给basseException
但在赋值的右侧使用它(仍然为空))弄糊涂了我知道这正在改变逻辑,只是为了测试
甚至尝试(但我不相信这会欺骗声纳)
尝试更改
chain()
以帮助您:想想看,几乎不可能成为问题-几乎微不足道的是
a
不是null
这里# 2 楼答案
我会尝试看看它是否有效: