Stop on specific NullPointerException in Eclipse

TL;DR: Find the line where the exception occurs and then add a conditional breakpoint which checks the local variables for values that would trigger the exception.

In Eclipse, you can stop on any exception by using the menu Run -> “Add Java Exception Breakpoint…“.

That’s great but it doesn’t help when you want to stop on a certain exception on a certain line. It’s a big problem with code that uses exceptions for control flow – you could have thousands of those exceptions before you get to the one which you care about.

In my case, I had a NullPointerException in java.util.concurrent.ConcurrentHashMap:

    public V get(Object key) {
        Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek;
        int h = spread(key.hashCode()); <-------- key is null
        ...

I tried to add a conditional breakpoint here with the condition key == null but Eclipse complained that it couldn’t compile the expression (probably missing debug information).

The method was called from Jetty’s ClassInheritanceHandler, so I added a conditional breakpoint there.

That’s another reason to copy method results into local variables before using them.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: