Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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?

share|improve this question
    
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. –  user117 Feb 15 '13 at 17:51
add comment

7 Answers 7

up vote 2 down vote accepted

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

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 soon to be 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) {
    checkNotNull(param1, param2, param3);
    ...
}

public static void checkNotNull(Object... objects) {
    if (asList(objects).contains(null)) {
        throw new IllegalArgumentException();
    }
}

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.

share|improve this answer
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. –  Nick Hodges Feb 15 '13 at 16:48
add comment

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

share|improve this answer
    
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 Feb 15 '13 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. –  mikeTheLiar Feb 15 '13 at 17:21
add comment

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.
share|improve this answer
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 Feb 15 '13 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. –  Michael Kjörling Feb 15 '13 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." –  Thomas Eding Feb 15 '13 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). –  Michael Kjörling Feb 15 '13 at 18:22
add comment

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.

share|improve this answer
    
I mean instead of showing a Stack trace error how can we make the user more understandable about the Null pointer that happened @deadmg –  nigel thomas Feb 15 '13 at 10:34
3  
@nigelthomas - here DeadMG means the programmer calling your code (which might be you) not the application user –  Mark Feb 15 '13 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 Feb 15 '13 at 14:44
add comment

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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