24

I am using eclipse and programing in java. Sometimes I come across a nullPointerException that will plague me for hours. Is there anyway to debug nullPointerExceptions better and figure out what variable values are and other things that would cause null Pointer Exceptions.

Noah Huppert
  • 4,028
  • 6
  • 36
  • 58
  • 3
    look at the stack trace... it shows what line threw the NPE and you can put a break point there and see what variable is null... – chancea Jul 26 '13 at 02:17
  • The best way to learn how to debug NPE is to keep debugging them. You will get better at it with time. But the key is to find out where it's occurring and then check the variables. No magic here. – Hovercraft Full Of Eels Jul 26 '13 at 02:17
  • 1
    You could place `assert` statements into your code – MadProgrammer Jul 26 '13 at 02:17
  • Uh, look at the exception trace and see where the error is raised. Put a stop there (or insert print statements) to figure out what value is null. Trace that value back to its source. – Hot Licks Jul 26 '13 at 02:17
  • 1
    Doesn't the exception tell you what line had the error? Any given line of code shouldn't be doing a whole lot, and any given function should ideally only have a few lines of code (or otherwise be very simple even if it has many lines). It shouldn't be hard to identify where the null value originated in any given function. – David Jul 26 '13 at 02:19
  • My problem is that with a function like function(a, b, c, d, e) it does not tell you which one of those variables is null. – Noah Huppert Jul 26 '13 at 02:25
  • @NoahHuppert: makes no sense. The stack trace will tell you the line of the NPE, and your debugger or logger or println will tell you which reference variable is null. – Hovercraft Full Of Eels Jul 26 '13 at 02:28
  • @HovercraftFullOfEels I was asking if there was any debugger or logger that would help me. – Noah Huppert Jul 26 '13 at 02:35
  • @NoahHuppert: **any** debugger or logger will help you. Just give them a try. But again, there is no magic, you just have to trace the NPE to its source. – Hovercraft Full Of Eels Jul 26 '13 at 02:35

3 Answers3

34

Look at the stack trace and read the line number where the NullPointerException is thrown. Almost always, the line has some method invocation like

x.getValue()

If x is null, you get a NullPointerException. If the method at the top of the stack trace is not your code, trace the stack all the way back until you do reach your code. Very often in this case, you are passing null to a method that doesn't like null parameters. Find it and fix it.

Also, very often when you encounter a method that is not yours that is throwing a NullPointerException, read the documentation. For example, look at String.replace(CharSequence target, CharSequence replacement):

Throws:

NullPointerException - if target or replacement is null.

It doesn't get much clearer than that!

Here's an example:

enter image description here

Looking at line 4, we see foo.bar(). This implies that foo is null. That one is easy. Let's look at another example:

enter image description here

Tracing back to your code, we see that s.replace(target, replacement) is throwing. We should inspect target and replacement. Let's attach a debugger:

enter image description here

Aha! replacement is null. You can do the same thing in Eclipse. Set a breakpoint for when an exception is thrown, and use it to inspect the parameters to your method. I'm primitive here because I come from a school of thought where I genuinely believe everyone would be better off if they learned to do it the hard way first. Leaky abstractions and all that.

Community
  • 1
  • 1
jason
  • 236,483
  • 35
  • 423
  • 525
19
  1. While debugging can you use the BreakPoints view, to capture the null pointers.

    Window -> Show View -> Breakpoints

    In the view there is a "J!" that lets you set breakpoints on exceptions. You can set java.lang.NullPointerException. So once null pointer exception is thrown, you can check which variable is causing null.

  2. Other thing you can do is capture possible null pointer access while you are coding. Off-course you cant capture all the Null Pointers using this setting. But still its helpful, set the following settings in your eclipse.

    Preferences -> Java -> Compiler -> Errors/warnings -> Null analysis

Jayamohan
  • 12,734
  • 2
  • 27
  • 41
  • It may also be a debug setting in eclipse that is halting program execution on uncaught exceptions. See answer: https://stackoverflow.com/a/32606736/2544255 – Olmstov Mar 04 '19 at 18:48
4

There are a few ways to make NullPointerException less of an issue:

  1. Use the @Nullable annotation.

  2. Test the values of arguments for null in constructors and setters (avoid setters in plain old Java code). If you do this a lot you could make an (Eclipse) source code template to quickly generate the code. This is called "failfast" - you don't wait for the exception to be thrown when the value is being used further in the code, e.g. after storing it in a field.

  3. Make sure that you perform a minimum amount (e.g. 1 or 2) of operations per line. If you don't you will have to find out where in the single line expression the NullPointerException occurred.

  4. Don't use null in fields to indicate state. Instead, use e.g. an enum State. E.g. don't do if (socket == null) { // not connected } as it easy to forget to check for null later on. A explicit state is not so easy to forget.

  5. Don't initialize local variables to null unless explicitly needed. Actually, if you handle your scope and exceptions correctly you should be able to mark most variables final. Replacing the default printStacktrace() methods with throw new IllegalStateException("Unhandled program state", e) helps because it is seen as an exit point of a code block.

After a lot of programming you will find the number of NullPointerExceptions go down.

Community
  • 1
  • 1
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263