I have a bug raised by sonar cube on following code :
private request = null; try { request = createRequest(); // create Request log.info(" Request created with details "+request.toString()); } catch(...) { } catch(Exception e) { }
The bug is raised at log.info statement as it suggests to check request for NULL before using. But my doubt is in case I check it for null and if it is actually null, then I would like it to goto catch exception block, which anyhow it will go in case I dont check explicitly for NULL. So is it false positive?How can i handle this?
Advertisement
Answer
I don’t think this is a false positive. request
can be null in your code so calling toString
on it will cause the null pointer exception to be thrown.
If createRequest
can return null then you should explicitly check for it rather than just rely on the log statement. Something like the following.
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) { }
On a side note, I find catching Exception
like you are doing in your snippet is generally a bad idea. I can’t see enough of the context of your code to know if that is true in your case, but it’s something that you should probably take a look at.