NullPointerException vs '= null' check

Discussion in 'Java' started by jstorta, Feb 19, 2006.

  1. jstorta

    jstorta Guest

    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
    jstorta, Feb 19, 2006
    #1
    1. Advertising

  2. jstorta wrote:
    > 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.
    Andrew McDonagh, Feb 19, 2006
    #2
    1. Advertising

  3. jstorta

    Ian Mills Guest

    Andrew McDonagh wrote:
    > jstorta wrote:
    >> 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.
    >

    That would certainly be my preference as well.
    Ian Mills, Feb 19, 2006
    #3
  4. jstorta

    VisionSet Guest

    "jstorta" <> wrote in message
    news:...
    >
    > 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
    VisionSet, Feb 19, 2006
    #4
  5. jstorta

    Jacob Guest

    jstorta wrote:
    > 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.
    Jacob, Feb 19, 2006
    #5
  6. 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
    --
    Q276304 - Error Message: Your Password Must Be at Least 18770 Characters
    and Cannot Repeat Any of Your Previous 30689 Passwords -- RISKS 21.37
    Dimitri Maziuk, Feb 19, 2006
    #6
  7. jstorta

    Roedy Green Guest

    On 19 Feb 2006 09:08:21 -0800, "jstorta" <> wrote,
    quoted or indirectly quoted someone who said :

    >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.
    --
    Canadian Mind Products, Roedy Green.
    http://mindprod.com Java custom programming, consulting and coaching.
    Roedy Green, Feb 19, 2006
    #7
  8. 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.
    widernet programmer, Feb 19, 2006
    #8
  9. jstorta

    James McGill Guest

    On Sun, 2006-02-19 at 09:08 -0800, jstorta wrote:
    >
    > 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
    James McGill, Feb 20, 2006
    #9
  10. jstorta

    Chris Smith Guest

    James McGill <> wrote:
    > 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
    Chris Smith, Feb 20, 2006
    #10
  11. jstorta wrote:
    > 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
    tom fredriksen, Feb 23, 2006
    #11
  12. jstorta

    javaBro

    Joined:
    Jan 15, 2013
    Messages:
    1
    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"?
    javaBro, Jan 15, 2013
    #12
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jon A. Cruz

    Re: NullPointerException Error??

    Jon A. Cruz, Jul 6, 2003, in forum: Java
    Replies:
    0
    Views:
    508
    Jon A. Cruz
    Jul 6, 2003
  2. Replies:
    5
    Views:
    26,486
    Mike Schilling
    Mar 29, 2006
  3. G Fernandes
    Replies:
    9
    Views:
    572
    DHOLLINGSWORTH2
    Feb 27, 2005
  4. Daniel Pitts
    Replies:
    24
    Views:
    841
  5. Mike
    Replies:
    12
    Views:
    701
    Daniel Pitts
    Sep 26, 2008
Loading...

Share This Page