1

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)

6
  • Have you initialized the w and stat variables? Does stat.getData() actually return data? (I'm assuming s was supposed to be stat and you just typed it wrong in the question. Is that correct?) Commented Oct 5, 2015 at 18:58
  • Is there an error stacktrace? Commented Oct 5, 2015 at 18:58
  • Add null checks for both the writer and stat objects e. g. If(w ! =null & & s ! = null) after entering the try block Commented Oct 5, 2015 at 18:58
  • you should debug or add some print statement to see what the values of w, and s are. if these input parameters are null you cant do much about this. other than throw an exception Commented Oct 5, 2015 at 18:59
  • @Keith sorry, that was a type in creating the question. stat.getData() is actually s.getData() and yes, it does return data. w and s are provided in the method call. Commented Oct 5, 2015 at 19:00

1 Answer 1

3

You need both Writer wand 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"); ... 
Sign up to request clarification or add additional context in comments.

10 Comments

You should add that although the Stat object may be constructed, its getData() may be returning null, too.
this is double exception checking, ie the NullPointerException is ALSO doing this check. Better IMO if you are going to go this route would be to put try {} catch {} blocks around the lines where you could get the nullpointerexceptions, catch the NPEs, and throw an IllegalArgumentException initialized with the NPE exception
@Keith I don't think that this belongs into the sanitizing of arguments. writeFile.write(s.getData());does not throw a NPE if s.getData() returns null.
Thanks for this, turns out that I was only thinking about the cases where w could be null, but it turns out the problem was being caused by s.
@DTR glad that you found it
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.