A null pointer exception occurs when a method is invoked against an object that has a null value. Java seems to completely lose its mind and just print java.lang.NullPointerException and a class name. There's no stack trace and there's no line number. It's a bummer. You've been sniped by a NPE.
Like any good sniper, a NPE hides itself. You can tell the direction from where it came and that it happened, but that's about it.
The best way to deal with NPEs is to prevent them from happening. The way I try to do this is to assume that someone is going to pass a null value as one of the arguments and I assume that null could be returned by any one of my method invocations I'm pretty well covered.
Another trick I like to do is to flip values in equals methods, for example, I 'll go:
"value".equals(variable) instead of variable.equals("value")
by invoking the equals method on the String constant a NPE will never occur even if variable is null.
Luckily we all write awesome code so this never happens, but when we need to look at other people's code to find them I use the following technique. It's a divide and conquer technique that has served me well.
- Make it repeatable--find a way to repeat the use case consistently
- With your favorite debugger--use Eclipse if you don't have a favorite
- Step over each line until you hit your NPE
- Once you hit the NPE, put a break point on the line where the NPE occurred
- Uncheck the last iteration's last good break point.
- Rerun your use case
- Step into the line where the last NPE was thrown
- Repeat from step 3 until you find the cause
No comments:
Post a Comment