Sonarqube "null pointer exception could be thrown":误报?
Sonar Cube "null pointer exception could be thrown" : False positive?
我有一个声纳立方体在以下代码中引发的错误:
private request = null;
try
{
request = createRequest(); // create Request
log.info(" Request created with details "+request.toString());
}
catch(...)
{
}
catch(Exception e)
{
}
错误出现在 log.info 语句中,因为它建议在使用前检查请求是否为 NULL。但我怀疑是万一我检查它是否为 null,如果它实际上是 null,那么我希望它转到 catch 异常块,无论如何它都会去,以防我不明确检查 NULL。那么这是误报吗?我该如何处理?
我认为这不是误报。 request
在您的代码中可以为 null,因此对其调用 toString
将导致抛出空指针异常。
如果 createRequest
可以 return null 那么你应该明确地检查它而不是仅仅依赖日志语句。类似于以下内容。
private request = null;
try
{
request = createRequest(); // create Request
if ( null == request ){
throw new NullRequestException();
}
log.info(" Request created with details "+request.toString());
}
catch(...)
{
}
catch(Exception e)
{
}
附带一提,我发现像您在代码片段中所做的那样捕获 Exception
通常不是一个好主意。我看不到你的代码的上下文,无法知道你的情况是否属实,但你可能应该看看它。
我有一个声纳立方体在以下代码中引发的错误:
private request = null;
try
{
request = createRequest(); // create Request
log.info(" Request created with details "+request.toString());
}
catch(...)
{
}
catch(Exception e)
{
}
错误出现在 log.info 语句中,因为它建议在使用前检查请求是否为 NULL。但我怀疑是万一我检查它是否为 null,如果它实际上是 null,那么我希望它转到 catch 异常块,无论如何它都会去,以防我不明确检查 NULL。那么这是误报吗?我该如何处理?
我认为这不是误报。 request
在您的代码中可以为 null,因此对其调用 toString
将导致抛出空指针异常。
如果 createRequest
可以 return null 那么你应该明确地检查它而不是仅仅依赖日志语句。类似于以下内容。
private request = null;
try
{
request = createRequest(); // create Request
if ( null == request ){
throw new NullRequestException();
}
log.info(" Request created with details "+request.toString());
}
catch(...)
{
}
catch(Exception e)
{
}
附带一提,我发现像您在代码片段中所做的那样捕获 Exception
通常不是一个好主意。我看不到你的代码的上下文,无法知道你的情况是否属实,但你可能应该看看它。