I am learning JAVA.
I cannot seem to find a way to get rid of this 'possible null derefence' warning. I have created fOut in the proper scope as null, otherwise I get a 'may not have been initialized' error.
I was unable to find an simple example that would help me fix this. I know it is probably a simple answer.
Thank you.
public static int waveToFile (String filename, byte[] byteWave)
{
FileOutputStream fOut = null;
File file = new File (filename);
try
{
fOut = new FileOutputStream(file);
}
catch (IOException e)
{
}
try{
fOut.write(byteWave); //THIS IS WARNING of POSSIBLE DE-REFERENCE
fOut.close(); //OF NULL POINTER
}
catch (IOException e)
{
}
return mErr;
}
The fact is that you are constructing the file object and using it in two different try-catch blocks. So if this fails:
no value will be assigned to
fOut
, the firstcatch
will handle the exception and the excution will continue with:Hah!
fOut
isnull
because the previous block failed. The warning is well justified.First of all, wrap the two operations in the same try-catch block:
This piece of code has still a problem: if
write
fails and an exception is thrown,close
will never be called. You can use afinally
block to ensure that the file is closed no matter what or, better, a closing context: