NullPointerException is a run-time exception which is not recommended to catch it, but instead avoid it:

if(someVariable != null) someVariable.doSomething();
else
{
    // do something else
}
Answer from Eng.Fouad on Stack Overflow
🌐
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. This would then be caught by the try-catch block.
Discussions

java - Catching null pointer exceptions - Stack Overflow
The try...catch block is assuming the value is valid, and if it isn't, it falls through to work around the aberrant behavior. Exceptions should primarly be considered when aberrant, program-breaking code occurs (divide-by-zero, etc). ... Sign up to request clarification or add additional context in comments. ... No, those code blocks are not the same at all. In the first code block, you are checking if myVariable is null... More on stackoverflow.com
🌐 stackoverflow.com
java - Null Pointer exception within a try catch block - Stack Overflow
Getting the following runtime error, causing my application to crash on launch E FATAL EXCEPTION: MonitoringThread 13533 AndroidRuntime E Process: foo.com, PID: 13533 13533 More on stackoverflow.com
🌐 stackoverflow.com
Is it a acceptable approach to put try catch wherever null pointer exception occurs? - Software Engineering Stack Exchange
There is just no excuse for a NPE, ... quality Java code. ... +1 Every time I see a notification about a NPE as an end user I want to smack whoever wrote that particular piece of code. ... It depends on the code block, but yes, in many cases try-catch is a good solution to handle a number of null-pointer related bugs you are not prepared to address individually. You need to fulfill two conditions to make exceptions ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
February 15, 2013
Eliminating Null Pointer Exceptions
IMO, the existence of null pointers in a memory safe language is contrary to its purpose. Null pointers are memory safety. They prevent you from doing the memory unsafe thing of referencing unintialized memory. More on reddit.com
🌐 r/java
91
0
June 24, 2024
🌐
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 ...
🌐
OWASP Foundation
owasp.org › www-community › vulnerabilities › Catch_NullPointerException
Catch NullPointerException | OWASP Foundation
The program explicitly throws a NullPointerException to signal an error condition. The code is part of a test harness that supplies unexpected input to the classes under test. Of these three circumstances, only the last is acceptable. ... The following code is what a programmer might mistakenly do and should avoid (this is an oversimplified example). try { UserSession user = Server.Session.getUserLoginSession(); Server.sendText("Hello "+ user.getName()); } catch (NullPointerException npe) { Server.sendText("Please login"); }
Top answer
1 of 8
7

If you're using third party code that is returning null, it's much better to check the return value.

ThirdPartyValue thirdPartyValue = thirdParty.getValue();
if (null == thirdPartyValue) {
    ...
}

Edit: Java 8 is out! This should now be

Optional<ThirdPartyValue> thirdPartyValue = Optional.ofNullable(thirdParty.getValue());

A NullPointerException is insidious and misleading, because it means you have an error somewhere else, where a variable was set to null without you expecting it to be.

I repeat, the bug isn't where the NullPointerException was thrown, the bug is earlier in your code, where a variable was set to null without you expecting it to be.

Catching the NullPointerException means you're hiding or excusing the actual bug.

In your own code, it is much better to do away with null whereever possible, and for that matter, also mutable variables.

If you get an exception, don't catch it and return null, instead wrap and rethrow the exception.

If you have a method that should sometimes not return a value, you could return an empty Collection, or an Optional, which is new in Java 8.

If you never set a variable to null you can never have an unexpected null.

Don't allow null parameters:

public void method(A param1, B param2, C param3) {
    requireNonNull(param1, param2, param3);
    ...
}

public static void requireNonNull(Object... parameters) {
    Stream.of(parameters).forEach(Objects::requireNonNull);
}

Avoid creating "result" variables that are temporarily null:

Instead of:

public Result method() {
    Result result = null;    // <- this smells
    try {
        result = ...;
    } catch (SomeException e) {
        LOGGER.log(Level.WARNING, "Exception "+e.getMessage(), e);
    }
    return result;
}

you should:

public Result method() {
    try {
        return ...;
    } catch (SomeException e) {
        throw new MyPossiblyRuntimeException(e);
    }
}

Sooner or later you will start to see usage of null (and mutable variables) as a code smell.

I'm sure you can come up with other smart ways to avoid null, be creative!

tl;dr: NullPointerException should never be thrown in the first place, so don't catch it, because that means you're hiding the actual bug.

2 of 8
22

Regarding your comment:

I mean instead of showing a Stack trace error how can we make the user more understandable about the Null pointer that happened.

The user neither knows nor cares about what a Null pointer is. If a NullPointerException occured, it's a bug in your code. It should be caught and logged by the global exception handler, then the bug should be fixed and an update should be shipped.

(You do use a global, catch-all exception handler that logs the exception, apologizes to the user, terminates the application and instructs the user how to send the stack trace to you, right? If not, this might be a good time to start.)

Find elsewhere
🌐
Quora
quora.com › Is-it-bad-practice-to-catch-null-pointer-exceptions-in-Java
Is it bad practice to catch null pointer exceptions in Java? - Quora
Answer (1 of 14): Yes, except maybe at the top level. One glaring issue: you can't guarantee that the NPE you caught was due to the specific thing you expected might be null. The program might be causing other NPEs, and those are bugs that should be fixed. If you catch all NPEs and ignore them, ...
🌐
Educative
educative.io › answers › how-to-resolve-the-javalangnullpointerexception
How to resolve the java.lang.NullPointerException
This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it. In some cases, the compiler prevents this exception with the compile-time error “The variable might ...
🌐
Coderanch
coderanch.com › t › 615939 › java › null-pointer-exception-type-exception
Is null pointer exception the only type of exception we are not supposed to catch? (Java in General forum at Coderanch)
July 16, 2013 - We should never put try catch around runtime exceptions although java allows that(in that case I suppose it is only for internal working of java not for us) No, not at all.
🌐
GeeksforGeeks
geeksforgeeks.org › java › null-pointer-exception-in-java
Null Pointer Exception in Java - GeeksforGeeks
6 days ago - Explanation: The variable s contains null, so it does not refer to a String object. When s.length() is called, Java cannot invoke the method on a non-existent object and throws NullPointerException.
🌐
SEI CERT
wiki.sei.cmu.edu › confluence › display › java › ERR08-J.+Do+not+catch+NullPointerException+or+any+of+its+ancestors
ERR08-J. Do not catch NullPointerException or any of its ancestors | CERT Secure Coding
Programs must not catch java.lang.NullPointerException . A NullPointerException exception thrown at runtime indicates the existence of an underlying null pointer dereference that must be fixed in the application code (see EXP01-J. Do not use a null in a case where an object is required for ...
🌐
CodingTechRoom
codingtechroom.com › question › -handle-null-pointer-exceptions-try-catch-java
How to Handle Null Pointer Exceptions within a Try-Catch Block in Java? - CodingTechRoom
Understanding how to manage these exceptions using try-catch blocks is crucial for robust error handling and prevention of application crashes. ... public class Example { public static void main(String[] args) { try { String str = null; System.out.println(str.length()); // Throws NullPointerException } catch (NullPointerException e) { System.out.println("Caught a Null Pointer Exception: " + e.getMessage()); } } }
🌐
How to do in Java
howtodoinjava.com › home › exception handling › java nullpointerexception
Handling Java NullPointerException and Best Practices
October 1, 2022 - Java NullPointerException (NPE) is an unchecked exception and extends RuntimeException. NullPointerException doesn’t force us to use a try-catch block to handle it. NullPointerException has been very much a nightmare for most Java developers. It usually pop up when we least expect them.
🌐
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. It occurs when your code tries to use a variable that doesn't point to any object and instead refers to nothing (null).
🌐
Scaler
scaler.com › home › topics › null pointer exception in java
Null Pointer Exception in Java - Scaler Topics
March 20, 2024 - We can handle null pointer exceptions ... the invalid object invocation. Q: How do you pass a NullPointerException in Java? A: We handle it using try-catch blocks or by adding null checks....
🌐
Udemy
blog.udemy.com › home › it & development › software development › understanding null pointer exception
Understanding Null Pointer Exception - Udemy Blog
April 14, 2026 - A null pointer exception crashes your program when code tries to use a reference variable pointing to null. This article covers how it occurs in Java and C#, and two ways to handle it: null checks and try-catch blocks. You'll know exactly why it happens and how to fix it.
🌐
Coderanch
coderanch.com › t › 701899 › java › Catch-NullPointer-Exception
Why Would Try Catch Still Allow a NullPointer Exception (Java in General forum at Coderanch)
November 7, 2018 - Dave Tolls wrote:It allows it because the line that is throwing the NullPointerException is outside the try block, so is not covered by it. In any case, even if it were inside that try/catch block you don't actually do anything with the exception and simply carry on.
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › java basics › exceptions
java.lang.NullPointerException - Examples Java Code Geeks - 2026
July 6, 2022 - Throwing null, as if it were a Throwable value. When you try to synchronize over a null object. The java.lang.NullPointerException is a RuntimeException and thus, the Javac compiler does not force you to use a try-catch ...
🌐
Medium
medium.com › @TechiesSpot › java-null-pointer-exception-causes-solutions-best-practices-and-key-points-80f4bd91a302
Java Null Pointer Exception: Causes, Solutions, Best Practices, and Key Points | by Techie's Spot | Medium
January 22, 2024 - They occur when you attempt to ... causes and implementing preventive measures is crucial for writing robust Java code. A Null Pointer Exception is a runtime exception that occurs when you try to access an object that is not instantiated (i.e., ...