Catching null pointer exceptions

Well, by itself, carryOn(MyVariable); won't ever throw a NPE, unless something else within carryOn is referencing a method or property call on a null instance.

Catching exceptions is more computationally expensive than first checking for it, as the generation of an exception requires a stack trace to be generated, etc.

I'd argue that it results in "cleaner" code as well.

See also: - Java try/catch performance, is it recommended to keep what is inside the try clause to a minimum? - Try Catch Performance Java


From my stance, I'm hesitant to consider these two code blocks equivalent in intent. Sure, they go through the same error handling, but that's a developer's decision more than anything else.

To me, the if is testing to see if a value can be used, and if it can't, it's working around the issue. 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).


You only use exceptions for exceptional occurrences. Go with the first block of code, not the second.


No, those code blocks are not the same at all.

In the first code block, you are checking if myVariable is null, and you are doing it at only one point in time. Later on, myVariable may become null and eventually throw a NullPointerException. If this happens, the second code snippet will catch the exception, but the first will not.

Furthermore, the second code snippet will catch NullPointerExceptions that may be thrown from anywhere in the call stack resulting from the carryOn(myVariable) call. This is terrible; you are swallowing an exception operating under the assumption that a particular variable is null when it may be something else entirely.

Use the first code snippet.