Reputation: 187
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;
}
Upvotes: 0
Views: 219
Reputation: 33116
The fact is that you are constructing the file object and using it in two different try-catch blocks. So if this fails:
fOut = new FileOutputStream(file);
no value will be assigned to fOut
, the first catch
will handle the exception and the excution will continue with:
fOut.write(byteWave); //THIS IS WARNING of POSSIBLE DE-REFERENCE
fOut.close(); //OF NULL POINTER
Hah! fOut
is null
because the previous block failed. The warning is well justified.
First of all, wrap the two operations in the same try-catch block:
FileOutputStream fOut = null;
File file = new File (filename);
try {
fOut = new FileOutputStream(file);
fOut.write(byteWave);
fOut.close();
}
catch (IOException e) {
// Do something
}
This piece of code has still a problem: if write
fails and an exception is thrown, close
will never be called. You can use a finally
block to ensure that the file is closed no matter what or, better, a closing context:
File file = new File (filename);
try (FileOutputStream fOut = new FileOutputStream(file)){
fOut.write(byteWave);
}
catch (IOException e) {
// Do something
}
Upvotes: 2
Reputation: 1593
you need two try block.
public static int waveToFile (String filename, byte[] byteWave)
{
FileOutputStream fOut = null;
File file = new File (filename);
try
{
fOut = new FileOutputStream(file);
fOut.write(byteWave);
if(fOut !=null){
fOut.close();
}
}
catch (IOException e)
{
}
return mErr;
}
Upvotes: 0
Reputation: 53869
If an exception is thrown fOut
can be null
. Therefore the compiler is warning you.
To avoid it, check that it is not null
:
finally {
if(fOut != null) {
fOut.close();
}
}
As a side note:
close
in a finally block to make sure it is executedfOut
if there has been an exceptionYou can also use a try-with-resources statement which is perfectly safe and does the work for you:
try(fOut = new FileOutputStream(file)) {
fOut.write(byteWave);
} catch(IOException e) {
// do something with e
}
Upvotes: 5