Interesting situation. I have a section of c开发者_Python百科ode that creates several ZipOutputStreams. As a safety check before I even think about writing anything I check thta my output streams have been correctly initialised:
ZipOutputStream countStream = null;
File countFile = null;
// other files
try {
countFile =
new File(savePath.getCanonicalPath() + savePath.separator + outputTag
+ "_COUNT_OUTPUTS.zip");
// other files
} catch (Exception e) {
outputLog.add("UNABLE TO FIND SAVE PATH");
return util.FILE_INVALID;
}
try {
// prepare outputs
if (countFile.exists() == true) {
countFile.delete();
} else {
}
countStream = new ZipOutputStream(new FileOutputStream(countFile));
// other files
} catch (Exception e) {
e.printStackTrace();
outputLog.add("UNABLE TO CREATE OUTPUT FILES");
return util.FILE_SAVE_FAIL;
}
if (countStream == null) {
outputLog.add("UNABLE TO CREATE OUTPUT FILES");
return util.FILE_SAVE_FAIL;
} else {
}
I dont especially see where the problem is in this code, but it throws up a warning on the null test: "Null comparison always yields false: The variable countStream cannot be null at this location". As far as I can see it, I have a variable initialised to null, then the creation of an outputstream is attempted, but isn't guaranteed to happen. ignoring the warning is easy enough, but I'd rather know how the compiler comes to the conclusion that countStream is guaranteed to be successfully created
K.Barad
The compiler is able to see that you cannot be null there since:
- in your
try
you've initialized it (countStream = new ....
) and - in your
catch
you've "return
"ed out of the method.
Hence, the code "if (countStream == null)
" can only be attained through normal flow after countStream
has been initialized to a non-null ZipOutputStream
.
When there is no Exception, the variable countStream will not be null. When there is an Exception, you return util.FILE_SAVE_FAIL
and the null check will not be performed. Hence, whenever the null check is performed, the result will always be false.
Slightly more formal: There are no code paths by which execution can reach your null check that result in countStream
being null when the check is performed.
What I understood from this code is countStream is null and thats why its giving warning that "Null comparison always yields false"
If you debug you will find this code always goes to else part because if (countStream == null) {
condition does not pass.
精彩评论