Reputation: 372
I am attempting to write a method that has to take in a Writer
object and use that to provide output to a file. The current code I have is throwing a NullPointerException
, presumably because either there is an error in how I am creating my BufferedWriter or else in some instances w
(the Writer
object) is being passed as null
. I have no control over what is passed as w
, and cannot change the exceptions that this method is able to throw.
My code is as follows:
public void write(Writer w, Stat s) throws IOException {
try{
BufferedWriter writeFile = new BufferedWriter(w);
writeFile.write(s.getData());
writeFile.flush();
} catch (IOException e){
...
}
}
Is there something I'm doing wrong?
(This assignment arises out of homework, but this question isn't the homework itself)
Upvotes: 1
Views: 3444
Reputation: 32990
You need both Writer w
and Stat s
to be not null. Therefore you should reject them if they are null.
public void write(Writer w, Stat s) throws IOException {
if (w == null)
throw new IllegalArgumentException("writer is null");
if (s == null)
throw new IllegalArgumentException("stats is null");
...
Upvotes: 3