JB Nizet answer is okay, but it uses map only for its side effects and not for the mapping operation, which is kind of weird. There is a method which can be used when you are solely interested in the side effects of something, such as throwing an exception: peek.

List<Parent> filtered = list.stream()
    .peek(Objects::requireNonNull)
    .filter(predicate)
    .collect(Collectors.toList());

And if you want your own exception just put a lambda in there:

List<Parent> filtered = list.stream()
    .peek(p -> { if (p == null) throw new MyException(); })
    .filter(predicate)
    .collect(Collectors.toList());

Note about non exhausted streams

Note that, regardless of if you use map or peek, you have to make sure that the stream is consumed in its entirety for all the elements to be checked! Otherwise the exception might not be thrown even if there are null elements.

Examples where all elements might not be checked:

  • limit is used.
  • allMatch is used.
  • The stream is filtered BEFORE the null check pipeline stage.

Checked Exceptions

If your exception is checked you can either check for null beforehand, if you don't mind traversing the list twice. This is probably best in your case, but might not always be possible.

if (list.contains(null)) throw new MyCheckedException();

You could also throw an unchecked exception in your stream pipeline, catch it and then throw the checked one:

try {
    ...
        .peek(p -> { if (p == null) throw new MyException(); })
    ...
} catch (MyException exc) {
    throw new MyCheckedException();
}
Answer from Lii on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › NullPointerException.html
NullPointerException (Java Platform SE 8 )
July 21, 2026 - Applications should throw instances of this class to indicate other illegal uses of the null object. NullPointerException objects may be constructed by the virtual machine as if suppression were disabled and/or the stack trace was not writable · Submit a bug or feature For further API reference ...
🌐
How to do in Java
howtodoinjava.com › home › exception handling › java nullpointerexception
Handling Java NullPointerException and Best Practices
October 1, 2022 - Instead use String.valueOf(object). Even if the object is null in this case, it will not give an exception and will print ‘null‘ to the output stream. An awesome tip to avoid NPE is to return empty strings or empty collections rather than null.
🌐
N47
north-47.com › home › null pointer exceptions in java 8
Null pointer exceptions in Java 8 — N47
April 10, 2019 - One possible solution for handling null pointer exceptions when the object is not present would be throwing a custom exception for the specific object.
🌐
DZone
dzone.com › coding › java › avoiding nullpointerexception in java 8
Avoiding NullPointerException in Java 8
August 26, 2019 - In this post, we explore some simple strategies to avoid the NullPointerException. Let's get started. Different languages provide different methods for checking. Unfortunately, Java is not among them. So, we have to check our variables and objects beforehand. Back in Java 7, there was a proposal to add a simplified method that checked for this exception.
Top answer
1 of 4
23

JB Nizet answer is okay, but it uses map only for its side effects and not for the mapping operation, which is kind of weird. There is a method which can be used when you are solely interested in the side effects of something, such as throwing an exception: peek.

List<Parent> filtered = list.stream()
    .peek(Objects::requireNonNull)
    .filter(predicate)
    .collect(Collectors.toList());

And if you want your own exception just put a lambda in there:

List<Parent> filtered = list.stream()
    .peek(p -> { if (p == null) throw new MyException(); })
    .filter(predicate)
    .collect(Collectors.toList());

Note about non exhausted streams

Note that, regardless of if you use map or peek, you have to make sure that the stream is consumed in its entirety for all the elements to be checked! Otherwise the exception might not be thrown even if there are null elements.

Examples where all elements might not be checked:

  • limit is used.
  • allMatch is used.
  • The stream is filtered BEFORE the null check pipeline stage.

Checked Exceptions

If your exception is checked you can either check for null beforehand, if you don't mind traversing the list twice. This is probably best in your case, but might not always be possible.

if (list.contains(null)) throw new MyCheckedException();

You could also throw an unchecked exception in your stream pipeline, catch it and then throw the checked one:

try {
    ...
        .peek(p -> { if (p == null) throw new MyException(); })
    ...
} catch (MyException exc) {
    throw new MyCheckedException();
}
2 of 4
4

Let’s start with the simplest solution:

if(list.contains(null)) throw new MyException();
result = list.stream().filter(predicate).collect(Collectors.toList());

If you suspect the list to contain nulls and even have a specialized exception type to flag this condition, a pre-check is the cleanest solution. This ensures that such condition doesn’t silently remain if the predicate changes to something that can handle nulls or when you use a short-circuiting stream operation that may end before encountering a subsequent null.

If the occurrence of null in the list still is considered a programming error that shouldn’t happen, but you just want to change the exception type (I can’t imagine a real reason for this), you may just catch and translate the exception:

try {
    result = list.stream().filter(predicate).collect(Collectors.toList());
}
catch(NullPointerException ex) {
    if(list.contains(null)) // ensure that we don’t hide another programming error
        throw new MyException();
    else throw ex;
}

This works efficient under the assumption that null references do not occur. As said, if you suspect the list to contain null you should prefer a pre-check.

🌐
Medium
medium.com › @reetesh043 › java-optional-avoiding-null-pointer-exceptions-made-easy-d44e34b7c3e1
Java Optional: Avoiding Null Pointer Exceptions Made Easy | by Reetesh Kumar | Medium
February 9, 2024 - In this case, we could use Optional to wrap the list, so that the code can handle the case where the list is empty gracefully. 2. Don’t use Optional as a return type from methods unless the absence of a value is a valid return value. For example, if we have a method that returns a user, we shouldn’t return an Optional<User>. Instead, we should return null if the user doesn’t exist.
🌐
TechBloat
techbloat.com › home › how to handle null pointer exception in java
How to Handle Null Pointer Exception in Java - TechBloat
December 7, 2025 - Third, consider using Optional ... design your classes and methods to minimize nulls. Use annotations like @NonNull and @Nullable to clarify intent, and enable static analysis tools to catch potential issues early. In sum, combine straightforward null checks, Java utilities, ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-avoid-nullpointerexception-in-java-using-optional-class
How to avoid NullPointerException in Java using Optional class? - GeeksforGeeks
August 6, 2025 - String value is not present Note: Hence this can be understood as an exception handling method for NullPointerException NullPointerException Handling using Optional class: ... // Java program to handle NullPointerException // using Optional Class import java.util.Optional; public class Example { public static void main(String[] args) { // Create a String of size 10 String[] a = new String[10]; // Define the a[1] element a[1] = "geeksforgeeks"; // Create an Optional Class instance // and get the state for a[1] element // for Null value Optional<String> check = Optional.ofNullable(a[1]); // If t
Find elsewhere
Top answer
1 of 2
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:

int 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:

Integer 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:

public 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:

doSomething(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:

// 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:

/**
  * @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:
class 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 2
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:

public 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.)

🌐
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(() -> ...
🌐
amitph
amitph.com › home › java › avoid nullpointerexception using java optional
Avoid NullPointerException using Java 8 Optional | amitph
November 22, 2024 - On top of this, Java Optional provides convenient methods to access the object value, return defaults, throw exceptions, or perform null checks. A Java method or a POJO should use the Optional type for potentially null objects meant for external consumption. For example, a field in a POJO or return type of a method. Their consumers can use the Optional instance to safely access the object without dealing with the null values or checks. // Consumer needs to handle nulls proactively.
🌐
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 - Instead, consider using the static String.valueOf method, which does not throw any exceptions and prints "null", in case the function’s argument equals to null. The ternary operator can be very useful and can help us avoid the NullPointerException. The operator has the form: ... First, the boolean expression is evaluated. If the expression is true then, the value1 is returned, otherwise, the value2 is returned. We can use the ternary operator for handling null pointers as follows:
🌐
Iamprafful
blog.iamprafful.com › 6-tips-and-tricks-to-avoid-null-pointer-exception
6 Tips and Tricks to avoid NullPointerException | Prafful Lachhwani
February 11, 2022 - One of the famous ways to avoid java.lang.NullPointerException is to add null checks wherever plausible. However, this approach will make your code bloated with null != something statements.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-handle-nullpointerexception-in-java
How to Handle NullPointerException in Java
July 13, 2020 - The idea is that, when you expect a value to be null, its better to put a null check on that variable. And if the value does turn out to be null, take an alternative action. This is applicable not only to strings, but to any other object in Java.
🌐
Tech with Maddy
techwithmaddy.com › how-to-handle-nullpointerexception-using-optional-class
How to Handle NullPointerException using Optional class
March 10, 2024 - Otherwise, we print a message saying, "The country is null." Since we haven't initialized the String array, the output would be: ... import java.util.Optional; public class Country { public static void main(String[] args) { String[] countries = new String[5]; countries[3] = "India"; Optional<String> checkCountry = Optional.ofNullable(countries[3]); if(checkCountry.isPresent()){ String country = countries[3].toUpperCase(); System.out.println(country); } else { System.out.println("The country is null"); } } }
🌐
Javatpoint
javatpoint.com › how-to-avoid-null-pointer-exception-in-java
How to avoid null pointer exception in Java - Javatpoint
How to avoid null pointer exception in Java with java tutorial, features, history, variables, object, programs, operators, oops concept, array, string, map, math, methods, examples etc.
🌐
DEV Community
dev.to › arpitmandliya › java-8-optional-a-way-to-avoid-nullpointerexception-10g1
Java 8 Optional: A way to avoid NullPointerException - DEV Community
April 11, 2019 - Java Server Side expert who recently loves React. ... Education: Well… that’s for another website. But I love to teach! ... What do I do? - my best! I do my best! ... Yes I feel the same. It’s like you need to know when to use it. What are the cases it’s good for. You might want to explore using it with map() it’s a powerful tool. ... Thanks for sharing! ... Yes, Optional.of will throw an Exception if you pass a null value.
🌐
GeeksforGeeks
geeksforgeeks.org › java › null-pointer-exception-in-java
Null Pointer Exception in Java - GeeksforGeeks
5 days ago - The best way to avoid NullPointerException is to identify where a reference can be null and handle that case before performing an operation on it.
🌐
Quora
quora.com › How-do-you-handle-a-null-pointer-exception-in-Java-using-try-catch
How to handle a null pointer exception in Java using try catch - Quora
Answer (1 of 3): Ideally all your null pointer exceptions happen during development and testing, never in production. So generally your program shouldn’t try to handle [code ]NullPointerException[/code]. Instead, you handle it by correcting the program so that any null pointers that occur ...