Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / February 2006

Tip: Looking for answers? Try searching our database.

NullPointerException vs '= null' check

Thread view: 
jstorta - 19 Feb 2006 17:08 GMT
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
Andrew McDonagh - 19 Feb 2006 17:19 GMT
> I have question regarding best practices.
>
[quoted text clipped - 39 lines]
>
> Thanks

definitely check for null, over letting an exception be thrown.
Ian Mills - 19 Feb 2006 17:22 GMT
>> I have question regarding best practices.
>>
[quoted text clipped - 41 lines]
>
> definitely check for null, over letting an exception be thrown.

That would certainly be my preference as well.
VisionSet - 19 Feb 2006 17:53 GMT
> 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.

--
Mike W
Jacob - 19 Feb 2006 18:02 GMT
> I have question regarding best practices.
>
[quoted text clipped - 35 lines]
> 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.
Dimitri Maziuk - 19 Feb 2006 19:01 GMT
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
Signature

Q276304 - Error Message: Your Password Must Be at Least 18770 Characters
and Cannot Repeat Any of Your Previous 30689 Passwords           -- RISKS 21.37

Roedy Green - 19 Feb 2006 20:31 GMT
>Use a try/catch block
>String makeUpper( String paramString ) {
[quoted text clipped - 17 lines]
>    }
>}

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

Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.

widernet programmer - 19 Feb 2006 21:02 GMT
    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.
James McGill - 20 Feb 2006 06:20 GMT
> 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
Chris Smith - 20 Feb 2006 14:51 GMT
> 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.

Signature

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

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation

tom fredriksen - 23 Feb 2006 13:33 GMT
> I have question regarding best practices.
>
[quoted text clipped - 3 lines]
>
> 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


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.