To check or not to check for NULL?

Discussion in 'Java' started by Mike, Sep 22, 2008.

  1. Mike

    Mike Guest

    That is the question!

    Should I always check for the null value after using the new operator
    to create a new object (of any type)?

    JButton button = new JButton("test");

    if (button== null)
    System.out.println("Errror Message");

    Or am I just wasting time?
    Mike, Sep 22, 2008
    #1
    1. Advertising

  2. -----BEGIN PGP SIGNED MESSAGE-----
    Hash: SHA1

    Mike schreef:
    > That is the question!
    >
    > Should I always check for the null value after using the new operator
    > to create a new object (of any type)?
    >
    > JButton button = new JButton("test");
    >
    > if (button== null)
    > System.out.println("Errror Message");
    >
    > Or am I just wasting time?


    You are. If the object could not created, an exception will be thrown.
    Useful thing, exceptions, it eliminates the need to check for return
    values.

    H.
    - --
    Hendrik Maryns
    http://tcl.sfs.uni-tuebingen.de/~hendrik/
    ==================
    Ask smart questions, get good answers:
    http://www.catb.org/~esr/faqs/smart-questions.html
    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v2.0.9 (GNU/Linux)
    Comment: Using GnuPG with SUSE - http://enigmail.mozdev.org

    iEYEARECAAYFAkjXuHgACgkQBGFP0CTku6P/CACdH9ZAmTjyU/izf2sCZIzx2iu2
    o8wAnRH6humlTfPQNP3gouU7x47s3o+Q
    =yRP0
    -----END PGP SIGNATURE-----
    Hendrik Maryns, Sep 22, 2008
    #2
    1. Advertising

  3. Mike wrote:
    > That is the question!
    >
    > Should I always check for the null value after using the new operator
    > to create a new object (of any type)?
    >
    > JButton button = new JButton("test");
    >
    > if (button== null)
    > System.out.println("Errror Message");
    >
    > Or am I just wasting time?


    A new either returns a new object or throws an exception or error. Most
    specifically, if there is no memory left, it will throw an
    OutOfMemoryError. There is no need, therefore, to check for null.

    --
    Beware of bugs in the above code; I have only proved it correct, not
    tried it. -- Donald E. Knuth
    Joshua Cranmer, Sep 22, 2008
    #3
  4. Hakan wrote:
    > The obvious answer seems to be
    >
    > try
    >
    > {
    > JButton button = new JButton("test");
    > }
    > catch (Exception e)
    > {
    > System.out.println("Error Message");
    > }


    If you want to get the out of memory case too, you'll have to catch
    OutOfMemoryError too. But I don't recommend trying to catch that since
    too many things can go wrong.

    Also, you will generally only need to catch the checked exceptions, at
    which point the compiler will complain if you don't catch.

    --
    Beware of bugs in the above code; I have only proved it correct, not
    tried it. -- Donald E. Knuth
    Joshua Cranmer, Sep 22, 2008
    #4
  5. Mike

    Lew Guest

    Hakan wrote:
    > > The obvious answer seems to be

    >
    > > try

    >
    > > {
    > >  JButton button = new JButton("test");
    > > }
    > > catch (Exception e)
    > > {
    > >  System.out.println("Error Message");
    > > }


    Joshua Cranmer wrote:
    > If you want to get the out of memory case too, you'll have to catch
    > OutOfMemoryError too. But I don't recommend trying to catch that since
    > too many things can go wrong.
    >
    > Also, you will generally only need to catch the checked exceptions, at
    > which point the compiler will complain if you don't catch.


    And do more than write to System.out with the error messsage. Logging
    is best, System.err is better than System.out, and the complete and
    utter failure to recover from or rethrow the exception will not help
    the program.

    --
    Lew
    Lew, Sep 22, 2008
    #5
  6. Mike

    Roedy Green Guest

    On Mon, 22 Sep 2008 08:13:49 -0700 (PDT), Mike <>
    wrote, quoted or indirectly quoted someone who said :

    >Should I always check for the null value after using the new operator
    >to create a new object (of any type)?


    No point. If the new fails you get an exception not a null.
    --
    Roedy Green Canadian Mind Products
    http://mindprod.com/politics/harper.html
    Anyone but Harper for Prime Minister of Canada
    Roedy Green, Sep 22, 2008
    #6
  7. Mike

    Tom Anderson Guest

    On Mon, 22 Sep 2008, Mike wrote:

    > That is the question!
    >
    > Should I always check for the null value after using the new operator
    > to create a new object (of any type)?
    >
    > JButton button = new JButton("test");
    >
    > if (button== null)
    > System.out.println("Errror Message");
    >
    > Or am I just wasting time?


    A 'new' expression will never, *ever* evaluate to null, so this is
    *always* a waste of time. This is not C - if there isn't enough memory,
    you get an OutOfMemoryError, not a null value.

    tom

    --
    curry in a sack
    Tom Anderson, Sep 22, 2008
    #7
  8. Mike

    Mike Guest

    Then, the question is- should one even catch "OutOfMemoryError" at all
    every time an object is created? What should be the right course of
    action? System.exit(1)?

    On Sep 22, 11:49 am, Joshua Cranmer <> wrote:
    > Mike wrote:
    > > That is the question!

    >
    > > Should I always check for the null value after using the new operator
    > > to create a new object (of any type)?

    >
    > > JButton button = new JButton("test");

    >
    > > if (button== null)
    > >   System.out.println("Errror Message");

    >
    > > Or am I just wasting time?

    >
    > A new either returns a new object or throws an exception or error. Most
    > specifically, if there is no memory left, it will throw an
    > OutOfMemoryError. There is no need, therefore, to check for null.
    >
    > --
    > Beware of bugs in the above code; I have only proved it correct, not
    > tried it. -- Donald E. Knuth
    Mike, Sep 26, 2008
    #8
  9. Mike

    Mike Guest

    Joshua,

    > If you want to get the out of memory case too, you'll have to catch
    > OutOfMemoryError too. But I don't recommend trying to catch that since
    > too many things can go wrong.


    So don't catch it (the Error- OutOfMemoryError ) all? And why would I
    need to catch the exception as the other person suggested? I thought
    new operator throws an Error, not an Exception. I'm not sure why Hakan
    suggested catching an Exception.

    On Sep 22, 1:39 pm, Joshua Cranmer <> wrote:
    > Hakan wrote:
    > > The obvious answer seems to be

    >
    > > try

    >
    > > {
    > >  JButton button = new JButton("test");
    > > }
    > > catch (Exception e)
    > > {
    > >  System.out.println("Error Message");
    > > }

    >
    > If you want to get the out of memory case too, you'll have to catch
    > OutOfMemoryError too. But I don't recommend trying to catch that since
    > too many things can go wrong.
    >
    > Also, you will generally only need to catch the checked exceptions, at
    > which point the compiler will complain if you don't catch.
    >
    > --
    > Beware of bugs in the above code; I have only proved it correct, not
    > tried it. -- Donald E. Knuth
    Mike, Sep 26, 2008
    #9
  10. Mike wrote:
    > Then, the question is- should one even catch "OutOfMemoryError" at all
    > every time an object is created? What should be the right course of
    > action? System.exit(1)?


    There's a reason that the OutOfMemoryError is an error--you shouldn't
    catch it, unless you have a very good reason.

    1. Almost anything can generate an OOM error. For example, calling a
    function that only puts locals on the stack might do it in extremely
    tight situations.
    2. The error might not be thrown in a convenient location.
    3. What would you do if you caught it? Try to free memory? If that's
    what you're thinking, try using Java's SoftReference which interfaces
    with the garbage collector itself. If you merely want to die, then the
    VM will do it for you if you don't catch. If you want to display an
    error message or do other handling, far better to unify it all at a
    top-level area (e.g., uncaught exception handlers) since your entire
    setup is most likely in pieces anyways.

    There's no real point to catching what should be a rare condition when
    recovery is impractical and the potential source is nearly every line of
    code.


    --
    Beware of bugs in the above code; I have only proved it correct, not
    tried it. -- Donald E. Knuth
    Joshua Cranmer, Sep 26, 2008
    #10
  11. -----BEGIN PGP SIGNED MESSAGE-----
    Hash: SHA1

    Joshua Cranmer schreef:
    > Mike wrote:
    >> Then, the question is- should one even catch "OutOfMemoryError" at all
    >> every time an object is created? What should be the right course of
    >> action? System.exit(1)?

    >
    > There's a reason that the OutOfMemoryError is an error--you shouldn't
    > catch it, unless you have a very good reason.
    >
    > 1. Almost anything can generate an OOM error. For example, calling a
    > function that only puts locals on the stack might do it in extremely
    > tight situations.
    > 2. The error might not be thrown in a convenient location.
    > 3. What would you do if you caught it? Try to free memory? If that's
    > what you're thinking, try using Java's SoftReference which interfaces
    > with the garbage collector itself. If you merely want to die, then the
    > VM will do it for you if you don't catch. If you want to display an
    > error message or do other handling, far better to unify it all at a
    > top-level area (e.g., uncaught exception handlers) since your entire
    > setup is most likely in pieces anyways.
    >
    > There's no real point to catching what should be a rare condition when
    > recovery is impractical and the potential source is nearly every line of
    > code.


    There are some cases where it makes sense to catch an OOME, for example
    in testing code in which you want to try out how big an input some code
    can handle, where you have a loop repeating with ever bigger inputs and
    if it throws an OOME, you break out of the loop and report the test
    results, or start the next test etc. In production code, however, I
    indeed see little use for it. You could think of an optional
    memory-intensive computation which you try and if it doesn’t succeed,
    you use some kind of back-up system.

    H.
    - --
    Hendrik Maryns
    http://tcl.sfs.uni-tuebingen.de/~hendrik/
    ==================
    Ask smart questions, get good answers:
    http://www.catb.org/~esr/faqs/smart-questions.html
    -----BEGIN PGP SIGNATURE-----
    Version: GnuPG v2.0.9 (GNU/Linux)
    Comment: Using GnuPG with SUSE - http://enigmail.mozdev.org

    iEYEARECAAYFAkjcx4oACgkQBGFP0CTku6MiCwCgzLnwcClNIRp44nlS78AZQVtX
    8EIAnj3mFEurhSZqgZvYiFwnyaZVA1FF
    =YE07
    -----END PGP SIGNATURE-----
    Hendrik Maryns, Sep 26, 2008
    #11
  12. Hendrik Maryns wrote:
    > There are some cases where it makes sense to catch an OOME, for example
    > in testing code in which you want to try out how big an input some code
    > can handle, where you have a loop repeating with ever bigger inputs and
    > if it throws an OOME, you break out of the loop and report the test
    > results, or start the next test etc. In production code, however, I
    > indeed see little use for it. You could think of an optional
    > memory-intensive computation which you try and if it doesn’t succeed,
    > you use some kind of back-up system.


    The problem with trying to catch OOME is that it can be thrown
    *anywhere.* Your computation may be the memory hog, but the error might
    be thrown when the GUI updates itself and therefore completely the wrong
    thread.

    --
    Beware of bugs in the above code; I have only proved it correct, not
    tried it. -- Donald E. Knuth
    Joshua Cranmer, Sep 26, 2008
    #12
  13. Mike

    Daniel Pitts Guest

    Joshua Cranmer wrote:
    > Hendrik Maryns wrote:
    >> There are some cases where it makes sense to catch an OOME, for example
    >> in testing code in which you want to try out how big an input some code
    >> can handle, where you have a loop repeating with ever bigger inputs and
    >> if it throws an OOME, you break out of the loop and report the test
    >> results, or start the next test etc. In production code, however, I
    >> indeed see little use for it. You could think of an optional
    >> memory-intensive computation which you try and if it doesn’t succeed,
    >> you use some kind of back-up system.

    >
    > The problem with trying to catch OOME is that it can be thrown
    > *anywhere.* Your computation may be the memory hog, but the error might
    > be thrown when the GUI updates itself and therefore completely the wrong
    > thread.
    >

    Although, if it is your alloc that fails specifically, that gives you
    some ability to handle it. The goal is to handle the case where you
    allocate "way too much", rather than "almost too much". ImageIO code
    does this I believe.

    --
    Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
    Daniel Pitts, Sep 26, 2008
    #13
    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. Replies:
    5
    Views:
    26,517
    Mike Schilling
    Mar 29, 2006
  2. G Fernandes
    Replies:
    9
    Views:
    577
    DHOLLINGSWORTH2
    Feb 27, 2005
  3. Cirene
    Replies:
    1
    Views:
    799
    Alexey Smirnov
    Jun 9, 2008
  4. jason
    Replies:
    13
    Views:
    861
    John B. Matthews
    May 14, 2010
  5. putty
    Replies:
    1
    Views:
    247
    putty
    Apr 5, 2005
Loading...

Share This Page