There are instances where the references to objects, fields, variables etc can be null and there might be a possible occurrence of Null Pointer exception occurring at that point.

Is is a permanent solution to put these code blocks which expect Null ponter exception to be put in a try catch block?

  • Depends of what is delivering that reference. If it is your own code, then it is bad code, you must fix it. If its an outside code, file or resource, you can catch NPE and notify the user about that external element.
    – S.D.
    Commented Feb 15, 2013 at 17:51

8 Answers 8


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) {

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.

  • 1
    Great answer -- exactly so. Never return null, never allow or expect things to be null, and for heavens sake, never set anything to null. Commented Feb 15, 2013 at 16:48

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

  • Best Answer! Indeed, what does it mean make the User understandable? 1. We wrote buggy code 2. We used interfaces we do not understand. 3. We used interfaces that are buggy? There is just no excuse for a NPE, and though it happens all the time in bad quality Java code.
    – Ingo
    Commented Feb 15, 2013 at 16:16
  • 1
    +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. Commented Feb 15, 2013 at 17:21

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

  1. Non-locality of handling: Don't use try-except when a simple if would suffice. Use try-except when the error occurs far from the place where it is handled, e.g. deep in the call stack or within a large block of code.
  2. Useful error handling: Do more than the default exception handler. Logically abort an operation with a useful error message. Handle the exception at a point where you can actually make an informed decision over the high-level process. In a MVC GUI application, the Controller is often a good place. Under no circumstances handle the exception close to the generating point, log it and forget about it - that's just useful for your logs.
  • 3
    I was first horrified by your positive answer, but, reading further, I found it sensible and well thought. My first reaction is because I often see newbies wrapping a statement with try / catch just to avoid a NPE! But you catch the issue at a higher level (and it can apply to any unexpected runtime exception, of course) to avoid the application to just crash in this case, and to log it (hide it from the user) to allow programmers to analyze it. The "silently fail" option has one drawback: it supposes logs are regularly scrutenized, and the application can fail to do what is expected.
    – PhiLho
    Commented Feb 15, 2013 at 11:20
  • 9
    Never catch an exception that you don't know how to handle is a good rule of thumb that I try to stick to.
    – user
    Commented Feb 15, 2013 at 15:14
  • 2
    @MichaelKjörling: You should revise that to "Never catch an exception that you don't know how to handle if you do not rethrow the exception." Commented Feb 15, 2013 at 17:28
  • @ThomasEding I did say it was a rule of thumb. Rethrowing the exception counts as not catching it, in my book (as long as it's actually rethrown; in C#, the difference between throw e; and throw; inside the catch block).
    – user
    Commented Feb 15, 2013 at 18:22

No. If someone passes a null pointer where you did not expect it, then that's a bug. Make them deal with the exception- it's their problem.

  • I mean instead of showing a Stack trace error how can we make the user more understandable about the Null pointer that happened @deadmg Commented Feb 15, 2013 at 10:34
  • 3
    @nigelthomas - here DeadMG means the programmer calling your code (which might be you) not the application user
    – mmmmmm
    Commented Feb 15, 2013 at 10:55
  • @DeadMG: If it was a bug in their could, you should have thrown an Invalid Argument exception (e.g., in C# you might throw an ArgumentNullException) when they passed you a null argument. A user-friendly library will tend to avoid throwing null pointer exception, since it is difficult for users to know if such exceptions are bugs in the library or in their own code.
    – Brian
    Commented Feb 15, 2013 at 14:44

There's no point in placing exception handling where you aren't really handling exceptions. It's a lot of extra code & makes following the program difficult. If you want to show 'friendly' errors to users, just have a top-level exception handler.


Using a try-catch block every time will make your code needlessly complicated and less readable. Besides, if your code is thought thoroughly, there usually shouldn't "unpredictable" null pointers.

In most cases a simple check if some variable is null is enough. If necessary, you could log a message if a variable is null.


The real answer is that it depends on the domain of the application.

Is it more important that it functions exactly to spec (Financial Hedging calculator giving wrong results) or is it more important that it stays up no matter what (e-commerce site with a fudged up header)?

In some business a slightly-wrong result is worse than no result at all. In those cases you want to fail fast loud and explicit when something unexpected and strange happens so that people who inspect the logs can do their work and the root cause can be found and fixed.

Meanwhile if that is not your situation, and the goal is maximum uptime then thiton's answer is the way to go.


Is is a permanent solution to put these code blocks which expect Null ponter exception to be put in a try catch block?

This sounds like the anti-pattern of using exceptions for control flow (specifically, null pointer exceptions).

So, no, it is not good programming practice to do this. When possible, your code should avoid raising a null pointer exception, and use break/return for control flow instead.

The only exception is when interfacing with a library that non-deterministially raises a null pointer exception to signal a certain type of error. In this case, the library is an example of the anti-pattern, and the only thing you can do is catch the exception, of course.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.