NullPointerException vs '= null' check

J

jstorta

I have question regarding best practices.

Let's say I am writing a method that takes a String parameter and
returns a formatted String.

For this discussion we'll use the following.

String makeUpper( String paramString ) {
return parameterString.toUpperCase();
}

If parameterString is null then the code will return a
NullPointerException. I have two ways to solve this problem.



Use a try/catch block
String makeUpper( String paramString ) {
try {
return parameterString.toUpperCase();
}
catch ( NullPointerException e ) {
return "-";
}
}


OR


Use an if/else condition
String makeUpper( String paramString ) {
if ( paramString != null ) {
return parameterString.toUpperCase();
}
else {
return "-";
}
}



As far as I know both will accomplish the same thing, but I am not sure
which is the best practice for such situations or if it just personal
preference.


If one is better than the other, please set me straight.

Thanks
 
A

Andrew McDonagh

jstorta said:
I have question regarding best practices.

Let's say I am writing a method that takes a String parameter and
returns a formatted String.

For this discussion we'll use the following.

String makeUpper( String paramString ) {
return parameterString.toUpperCase();
}

If parameterString is null then the code will return a
NullPointerException. I have two ways to solve this problem.



Use a try/catch block
String makeUpper( String paramString ) {
try {
return parameterString.toUpperCase();
}
catch ( NullPointerException e ) {
return "-";
}
}


OR


Use an if/else condition
String makeUpper( String paramString ) {
if ( paramString != null ) {
return parameterString.toUpperCase();
}
else {
return "-";
}
}



As far as I know both will accomplish the same thing, but I am not sure
which is the best practice for such situations or if it just personal
preference.


If one is better than the other, please set me straight.

Thanks

definitely check for null, over letting an exception be thrown.
 
V

VisionSet

jstorta said:
If parameterString is null then the code will return a
NullPointerException. I have two ways to solve this problem.

Generally you don't catch RuntimeExceptions you test/validate preventively.
You should document your methods accordingly, and infact proactively throw
RuntimeExceptions early if you decide your method can do nothing useful with
null or wish to impose a stricter regime on the method caller.
 
J

Jacob

jstorta said:
I have question regarding best practices.

Let's say I am writing a method that takes a String parameter and
returns a formatted String.

For this discussion we'll use the following.

String makeUpper( String paramString ) {
return parameterString.toUpperCase();
}

If parameterString is null then the code will return a
NullPointerException. I have two ways to solve this problem.



Use a try/catch block
String makeUpper( String paramString ) {
try {
return parameterString.toUpperCase();
}
catch ( NullPointerException e ) {
return "-";
}
}


OR


Use an if/else condition
String makeUpper( String paramString ) {
if ( paramString != null ) {
return parameterString.toUpperCase();
}
else {
return "-";
}
}



As far as I know both will accomplish the same thing, but I am not sure
which is the best practice for such situations or if it just personal
preference.

Neither of your alternatives throws any exceptions at all,
and neither is a good solution to whatever you try to acheive.

The first alternative is the infamous "design by exception" that
must be avoided.

Both alternatives masks a potential errors in that they
return a valid result from an invalid input. This must always
be avoided.

If it it is so that null is *not* a valid parameter value I see
three alternative solutions:

i) Assert on non-null. Use this only for a non-public method as
asserts are normally pruned in production code.

ii) Do nothing. This will eventually result in a NullPointerException
which is fine.

iii) Test for null and throw an IllegalArgumentException. Making this
an explicit test forces you to document it in the Javadoc and
this will complete the picture for your client.

I'd go for iii, and this is the approach I use "all the time" for my
public interfaces.
 
D

Dimitri Maziuk

jstorta sez:
I have question regarding best practices. [ ... catch vs if ... ]
If one is better than the other, please set me straight.

It depends on your application. If your expected "normal" input
is non-null strings you may want to not do either and let it
crash with NullPointerException (or catch NullPointer and throw
IllegalArgument).

From your description it sounds like null input is par for the
course. In that case "if" is usually preferrable as it does not
have the overhead of exception throw/catch.

IOW you want to throw exception only in exceptional circumstances
and catch it only if you can recover from it.

Dima
 
R

Roedy Green

Use a try/catch block
String makeUpper( String paramString ) {
try {
return parameterString.toUpperCase();
}
catch ( NullPointerException e ) {
return "-";
}
}


OR


Use an if/else condition
String makeUpper( String paramString ) {
if ( paramString != null ) {
return parameterString.toUpperCase();
}
else {
return "-";
}
}

The second is more idiomatic. The first would be faster code if you
got a null very rarely. The second would be faster if it nulls
appeared frequently. It takes quite a bit of futzing about to catch
an exception and almost no overhead to explicitly test for a null.

Exceptions are usually for things you want to deal with elsewhere.
 
W

widernet programmer

It would depend on what behavior you wanted your application to
have when a null string was encountered. From an object-oriented
perspective, you have to consider

1) what do you expect as input and
2) what do you want to happen when the null or non-null inputs are
encountered.

With respect to 2), if you want the app to continue when it finds a
null reference when it may otherwise crash, you want to throw an
exception. If you want some output to reflect the the null occurrence,
you could use either, but an 'if' would be the preferred method. Think
of exception handling as a way to decide if you want your app to stop,
continue, or go to some other flow of control (and/or write the actual
exception to output) in those rare cases where something unusual
happens. Using exceptions to to display output is bad pratice.
 
J

James McGill

If one is better than the other, please set me straight.

I would tend to avoid any situation that depends on catching an error
like NullPointerException. I regard that as trying to clean up around a
design flaw. I don't know, but I'd be willing to bet money that the
runtime exception is a lot more expensive than comparing a reference to
null. But there's the question of whether it's better to have a
failsafe trap even if it's heavy, than a compare that runs every time.

If you're getting down to that depth of optimization, you're looking at
bytecode anyway.

Comparing a ref to null is very likely to be one of the most efficient
operations in any implementation... JVM gurus can set me straight on
this, but I also would not assume that there's no impact of an exception
handler for an exception that's never thrown... And is it different for
RuntimeExceptions (like NPE?)

This short article is informative, even if it doesn't answer this
particular question
http://www.javaworld.com/javaworld/jw-08-2000/jw-0818-exceptions.html
 
C

Chris Smith

James McGill said:
If you're getting down to that depth of optimization, you're looking at
bytecode anyway.

Hopefully not... Bytecode is useless for optimization purposes.
Optimizations are performed in the JIT compiler while producing machine
code. Lowe-level optimization should be done with either VERY careful
microbenchmarks, or by obtaining the disassembly of the result of the
JIT compiler... which generally implies VM cooperation.
Comparing a ref to null is very likely to be one of the most efficient
operations in any implementation... JVM gurus can set me straight on
this, but I also would not assume that there's no impact of an exception
handler for an exception that's never thrown... And is it different for
RuntimeExceptions (like NPE?)

Well, you should always be skeptical when someone claims that something
has "no" impact. The possibility of an exception can prevent certain
optimizations from taking place, because the catch block needs to be in
a defined state and can access the state of local variables.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
T

tom fredriksen

jstorta said:
I have question regarding best practices.

Use a try/catch block

OR

Use an if/else condition

It depends on the situation

If it does not matter that it is a null and you can continue, the use an
if test to avoid the operation causing the null pointer exception.

But if you cannot continue if the argument is wrong then you can do one
of the following:

- throw an illegalArgument exception
where the catcher, if possible, tries to resolve the issue
and then retry
- return an null pointer, if that is of any use.

/tom
 
Joined
Jan 15, 2013
Messages
1
Reaction score
0
What about if you want to check null pointer in 4 or 5 objects and then do same action if any of them is null. Wouldn't catching NullPointerException and doing that action be easier (less code) than manually checking all nulls? Will that be breaking any "rules"?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,990
Messages
2,570,211
Members
46,796
Latest member
SteveBreed

Latest Threads

Top