If you're using a method that is documented as returning null
in some cases, then you should assign the result of the method to a variable (if you're going to use it for something else) and use ==
or !=
to test it for null. It is very poor programming practice to use the result as a reference and then rely on try/catch
on NullPointerException
to see if it's null
. For one thing, what if there's an unexpected null
somewhere else in the try
body? Now it will be catching the exception for the wrong reason. NullPointerException
always indicates a program bug. It should never be part of the "normal" program logic.
As for why it "kills the loop": It shouldn't. Even though your use of try/catch is poor practice, it should still work the way I think you intended, and shouldn't kill the loop. I just tested something similar to your code, but without l.readLine()
, and it seemed to behave. If you want the line number, it's l.getLineNumber()
, not l.readLine()
, which tries to read a line of text and could sabotage the Scanner
.