• Post Reply Bookmark Topic Watch Topic
  • New Topic

shrink a few lines of repeated code.  RSS feed

 
Willie Tsang
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is one method from Hashset Iterator. it returns the next object from the current one. I have a NullPointerException while running "if(current==null|current.next==null)" so I added the try and catch and it works. First question is, why am i getting the nullpointer exception if i have previously checked hasNext(). 2nd question, since the catch{} has the same code in the try{}, is it possilbe to strink some of the catch{}? Many Thanks.
 
William P O'Sullivan
Ranch Hand
Posts: 859
Chrome IBM DB2 Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What line in the above code caused the NPE?

WP
 
Willie Tsang
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
eclipse said "if(current==null|current.next==null)"
 
Paul Clapham
Sheriff
Posts: 22832
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Aha! Change this line of code from

to


Why? The "|" operator always evaluates both of its operands: so even if current == null is true, it will still look at current.next == true, thus throwing the NPE for current.next. Whereas the "||" operator will only evaluate its RHS if its LHS is false. The latter is what you want in this case, and frankly in almost every case.

And don't ever respond to NPE by writing code which catches it. A NullPointerException always indicates a programming error which should be found and fixed, rather than ignored and worked around.

(Of course when I say "don't ever" and "always" there, there are always exceptions to such things. But if it's your code, that isn't one of the exceptions.)
 
Willie Tsang
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks alot, that was a clear explainion. and thanks for the advice.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!