Firstly, you don't typically throw a NullPointerException.

This is an unchecked exception thrown when referencing a null value, which indicates a coding error rather than a recoverable condition.

Secondly, when you're not explicitly throwing the exception in your code, yet seeing it thrown anyway, it's likely that your value for current is null, hence current.next would throw it.

You could try a number of explicit exceptions to throw:

  • IndexOutOfBoundsException
  • NoSuchElementException
  • IllegalStateException
  • Etc. etc., or your own custom exception
Answer from Mena on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › null-pointer-exception-in-java
Null Pointer Exception in Java - GeeksforGeeks
September 8, 2026 - A NullPointerException (NPE) is ... value null. Since a null reference does not point to any actual object, calling its methods or accessing its fields causes the Java Virtual Machine (JVM) to throw a NullPointerExcept...
🌐
Medium
supakon-k.medium.com › 4-ways-to-handle-null-objects-in-java-7e2596c235d
4 ways to handle NullPointerException in Java | by Supakon_k | Medium
August 5, 2022 - when we use the stream method to process something, and after the method finishes the message and doesn’t have any data, we can throw the exception with the OrElseThrow method. ... String result = Optional.ofNullable(data).orElseThrow(() -> ...
Discussions

java - How to throw a null pointer exception and where - Stack Overflow
I think, need to check first, if ... by null pointer. ... There are also some annotations for non-null parameters. But the trend seems that non-null is in general assumed. In java 8 use Optional for possibly missing values. So a javadoc comment would be entirely sufficient. ... This does not seem to be a duplicate to me. ... Save this answer. ... Show activity on this post. This is opinionated, but imho it is better to throw it in the ... More on stackoverflow.com
🌐 stackoverflow.com
java - Is it okay to throw NullPointerException programmatically? - Stack Overflow
When there is a post-condition, that return value of a method must not be null, what can be done? I could do assert returnValue != null : "Not acceptable null value"; but assertions could be tur... More on stackoverflow.com
🌐 stackoverflow.com
java - What is a NullPointerException, and how do I fix it? - Stack Overflow
What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them? What methods/tools can be used to determine the cause so that you stop the exception from causing the progra... More on stackoverflow.com
🌐 stackoverflow.com
How do I avoid the NullPointerException in Mockito, jUnit testing?
I think calling mock(YourClass.class) returns a mock which upon calling its methods throws a NPE. This mean you should explicitly use doCallRealMethod(yourMock).when(yourMethod()) if you want the mock's method to behave like it normally would. By calling Mockito.spy(YourClass.class) it will create a mock which by default uses the real methods, if you don't specify otherwise More on reddit.com
🌐 r/javahelp
5
1
August 16, 2017
Top answer
1 of 16
74

I would recommend you never throw NullPointerException by yourself.

The main reason not to do this, as Thorbjørn Ravn Andersen says in a comment below, is that you don't wan't to mix 'real, bad NPEs' with NPEs thrown intentionally.

So, until you're confident that you're able to recognize 'valid' NPE, I'd recommend to use IllegalArgumentException when you want to tell to your API user that null is not a valid argument value. Your method's behavior when illegal null-parameter passed should be documented.

Another (more modern imho) option is to use @NotNull annotation near the argument. Here is an article about using @NotNull annotation.

As I mentioned earlier, there can also be cases, when throwing NPE will not be confusing either to you or to your teammates: NPE cause should be clear and recognizable.

For instance, if you use some library with preconditions module, like Guava, then I find using checkNotNull()-like methods is a preferable way to deal with illegally-passed nulls.

checkNotNull(arg, msg) throws NPE, but from the stacktrace it's quite clear, that it was produced by Preconditions.checkNotNull() and thus it's not an unknown bug but rather expected behavior.

2 of 16
44

I see no problem with throwing a NPE as early as possible before the JVM does it for you - in particular for null arguments. There seems to be some debate about this, but there are many examples in the Java SE libraries that does exactly this. I cannot see why NPE should be holy in the aspect that you are not able to throw it yourself.

However, I digress. This question is about something different. You are talking about a post-condition stating that the return value mustn't be null. Surely null in this case would mean you have a bug inside the very method?

How would you even document this? "This method throws a NullPointerException if the return value unexpectedly is null"? Without explaining how this could happen? No, I would use an assertion here. Exceptions should be used for errors that can conceivably happen - not to cover things that can happen if there's something wrong inside the method, because that does not help anybody.

🌐
Tutorialspoint
tutorialspoint.com › java › java_nullpointerexception.htm
Java - Null Pointer Exception
In output we can see the informative null pointer exception raised by the JVM. package com.tutorialspoint; import java.util.List; public class Tester { public static void main(String[] args) { // declare an employee without department Employee emp = new Employee(1,"Robert",null); // get department name of null department will // throw a NullPointerException String dept = emp.getDept().getName(); System.out.println(dept); } } class Employee { int id; String name; Department dept; Employee (int id, String name, Department dept){ this.id = id; this.name = name; this.dept = dept; } public int getI
🌐
Rollbar
rollbar.com › home › how to catch and fix nullpointerexception in java
How to Catch and Fix NullPointerException in Java
June 30, 2026 - NullPointerException is the most frequently thrown exception in Java applications, accounting for countless crashes.
Find elsewhere
Top answer
1 of 12
4227

There are two overarching types of variables in Java:

  1. Primitives: variables that contain data. If you want to manipulate the data in a primitive variable you can manipulate that variable directly. By convention primitive types start with a lowercase letter. For example variables of type int or char are primitives.

  2. References: variables that contain the memory address of an Object i.e. variables that refer to an Object. If you want to manipulate the Object that a reference variable refers to you must dereference it. Dereferencing usually entails using . to access a method or field, or using [ to index an array. By convention reference types are usually denoted with a type that starts in uppercase. For example variables of type Object are references.

Consider the following code where you declare a variable of primitive type int and don't initialize it:

Use with AIint x;
int y = x + x;

These two lines will crash the program because no value is specified for x and we are trying to use x's value to specify y. All primitives have to be initialized to a usable value before they are manipulated.

Now here is where things get interesting. Reference variables can be set to null which means "I am referencing nothing". You can get a null value in a reference variable if you explicitly set it that way, or a reference variable is uninitialized and the compiler does not catch it (Java will automatically set the variable to null).

If a reference variable is set to null either explicitly by you or through Java automatically, and you attempt to dereference it you get a NullPointerException.

The NullPointerException (NPE) typically occurs when you declare a variable but did not create an object and assign it to the variable before trying to use the contents of the variable. So you have a reference to something that does not actually exist.

Take the following code:

Use with AIInteger num;
num = new Integer(10);

The first line declares a variable named num, but it does not actually contain a reference value yet. Since you have not yet said what to point to, Java sets it to null.

In the second line, the new keyword is used to instantiate (or create) an object of type Integer, and the reference variable num is assigned to that Integer object.

If you attempt to dereference num before creating the object you get a NullPointerException. In the most trivial cases, the compiler will catch the problem and let you know that "num may not have been initialized," but sometimes you may write code that does not directly create the object.

For instance, you may have a method as follows:

Use with AIpublic void doSomething(SomeObject obj) {
   // Do something to obj, assumes obj is not null
   obj.myMethod();
}

In which case, you are not creating the object obj, but rather assuming that it was created before the doSomething() method was called. Note, it is possible to call the method like this:

Use with AIdoSomething(null);

In which case, obj is null, and the statement obj.myMethod() will throw a NullPointerException.

If the method is intended to do something to the passed-in object as the above method does, it is appropriate to throw the NullPointerException because it's a programmer error and the programmer will need that information for debugging purposes.

In addition to NullPointerExceptions thrown as a result of the method's logic, you can also check the method arguments for null values and throw NPEs explicitly by adding something like the following near the beginning of a method:

Use with AI// Throws an NPE with a custom error message if obj is null
Objects.requireNonNull(obj, "obj must not be null");

Note that it's helpful to say in your error message clearly which object cannot be null. The advantage of validating this is that 1) you can return your own clearer error messages and 2) for the rest of the method you know that unless obj is reassigned, it is not null and can be dereferenced safely.

Alternatively, there may be cases where the purpose of the method is not solely to operate on the passed in object, and therefore a null parameter may be acceptable. In this case, you would need to check for a null parameter and behave differently. You should also explain this in the documentation. For example, doSomething() could be written as:

Use with AI/**
  * @param obj An optional foo for ____. May be null, in which case
  *  the result will be ____.
  */
public void doSomething(SomeObject obj) {
    if(obj == null) {
       // Do something
    } else {
       // Do something else
    }
}

Finally, How to pinpoint the exception & cause using Stack Trace

What methods/tools can be used to determine the cause so that you stop the exception from causing the program to terminate prematurely?

Sonar with find bugs can detect NPE. Can sonar catch null pointer exceptions caused by JVM Dynamically

Now Java 14 has added a new language feature to show the root cause of NullPointerException. This language feature has been part of SAP commercial JVM since 2006.

In Java 14, the following is a sample NullPointerException Exception message:

in thread "main" java.lang.NullPointerException: Cannot invoke "java.util.List.size()" because "list" is null

List of situations that cause a NullPointerException to occur

Here are all the situations in which a NullPointerException occurs, that are directly* mentioned by the Java Language Specification:

  • Accessing (i.e. getting or setting) an instance field of a null reference. (static fields don't count!)
  • Calling an instance method of a null reference. (static methods don't count!)
  • throw null;
  • Accessing elements of a null array.
  • Synchronising on null - synchronized (someNullReference) { ... }
  • Any integer/floating point operator can throw a NullPointerException if one of its operands is a boxed null reference
  • An unboxing conversion throws a NullPointerException if the boxed value is null.
  • Calling super on a null reference throws a NullPointerException. If you are confused, this is talking about qualified superclass constructor invocations:
Use with AIclass Outer {
    class Inner {}
}
class ChildOfInner extends Outer.Inner {
    ChildOfInner(Outer o) { 
        o.super(); // if o is null, NPE gets thrown
    }
}
  • Using a for (element : iterable) loop to loop through a null collection/array.

  • switch (foo) { ... } (whether its an expression or statement) can throw a NullPointerException when foo is null.

  • foo.new SomeInnerClass() throws a NullPointerException when foo is null.

  • Method references of the form name1::name2 or primaryExpression::name throws a NullPointerException when evaluated when name1 or primaryExpression evaluates to null.

    a note from the JLS here says that, someInstance.someStaticMethod() doesn't throw an NPE, because someStaticMethod is static, but someInstance::someStaticMethod still throw an NPE!

* Note that the JLS probably also says a lot about NPEs indirectly.

2 of 12
972

NullPointerExceptions are exceptions that occur when you try to use a reference that points to no location in memory (null) as though it were referencing an object. Calling a method on a null reference or trying to access a field of a null reference will trigger a NullPointerException. These are the most common, but other ways are listed on the NullPointerException javadoc page.

Probably the quickest example code I could come up with to illustrate a NullPointerException would be:

Use with AIpublic class Example {

    public static void main(String[] args) {
        Object obj = null;
        obj.hashCode();
    }

}

On the first line inside main, I'm explicitly setting the Object reference obj equal to null. This means I have a reference, but it isn't pointing to any object. After that, I try to treat the reference as though it points to an object by calling a method on it. This results in a NullPointerException because there is no code to execute in the location that the reference is pointing.

(This is a technicality, but I think it bears mentioning: A reference that points to null isn't the same as a C pointer that points to an invalid memory location. A null pointer is literally not pointing anywhere, which is subtly different than pointing to a location that happens to be invalid.)

🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › NullPointerException.html
NullPointerException (Java Platform SE 8 )
July 21, 2026 - Java™ Platform Standard Ed. 8 ... Thrown when an application attempts to use null in a case where an object is required.
🌐
Scaler
scaler.com › home › topics › null pointer exception in java
Null Pointer Exception in Java - Scaler Topics
March 20, 2024 - The null pointer exception in java is a runtime exception, which is thrown when the program tries to use an object reference that is set to the null value.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-handle-nullpointerexception-in-java
How to Handle NullPointerException in Java
July 13, 2020 - If any of the arguments given in the function turn out to be null, the function would throw a NullPointerException.
🌐
Javatpoint
javatpoint.com › null-pointer-exception-in-java
Null Pointer Exception in Java - Javatpoint
Null Pointer Exception in Java with java tutorial, features, history, variables, programs, operators, oops concept, array, string, map, math, methods, examples etc.
🌐
Sentry
sentry.io › sentry answers › java › avoiding `nullpointerexception` in java
Avoid NullPointerException in Java with Null Checks | Sentry
October 1, 2026 - Accessing or modifying the field of a null object. Taking the length of null as if it were an array. Accessing or modifying the slots of null as if it were an array. Throwing null as if it were a Throwable value.
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › java basics › exceptions
java.lang.NullPointerException - Examples Java Code Geeks - 2026
July 6, 2022 - The following cases throw Null Pointer exception: Invoking a method from a null object. Accessing or modifying a null object’s field. Taking the length of null, as if it were an array.
🌐
Medium
medium.com › developers-journal › how-to-handle-null-pointer-exception-in-java-776ab2e0d8f5
How to Handle Null Pointer Exception in Java | by DJ | Developers Journal | Medium
January 27, 2022 - Notice that, when you declare a reference variable, you are really creating a pointer to an object. You must verify that the pointer is not null, before you request the method or a field from the object. Also, if the exception is thrown, use the information residing in the exception’s stack trace.
🌐
TutorialsPoint
tutorialspoint.com › why-can-i-throw-null-in-java-and-why-does-it-upcast-to-a-nullpointerexception
Why can I throw null in Java and why does it upcast to a NullPointerException?
July 2, 2020 - You can also throw a NullPointerException in Java using the throw keyword. public class ExceptionExample { public static void main(String[] args) { System.out.println("Hello"); NullPointerException nullPointer = new NullPointerException(); throw nullPointer; } }
🌐
How to do in Java
howtodoinjava.com › home › exception handling › java nullpointerexception: how to fix and avoid it
Java NullPointerException: How to Fix and Avoid It
October 10, 2026 - Throwing null as if it were an exception, for example throw error where error is null. Using null in a synchronized block. Assigning a null Integer to an int. Java converts the Integer to an int with a hidden method call (unboxing), and that ...
🌐
Frankel
blog.frankel.ch › throwing-a-nullpointerexception-or-not
Throwing a NullPointerException... or not
September 28, 2014 - Read the last sentence again: "Applications should throw instances of this class to indicate other illegal uses of the null object". It seems to be legal for an application to throw an NPE, even recommended by the Javadocs.
🌐
Delft Stack
delftstack.com › home › howto › java › null pointer exception in java
What Is a Null Pointer Exception in Java | Delft Stack
October 12, 2023 - In Java, the default value of any ... have any associate value. When a programmer tries to perform any operation with this reference variable, it throws a null pointer exception due to null conditions....
🌐
javaspring
javaspring.net › blog › null-pointer-exception-java
Understanding and Handling Null Pointer Exceptions in Java — javaspring.net
Use Defensive Programming: When writing methods, assume that the input parameters may be null and handle them appropriately. You can throw an appropriate exception, such as IllegalArgumentException, if a required parameter is null.