• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Resume loop after nullpointerexception

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi to all,
I am parsing an xml but the problem is that there are some tags that might or might not be in the xml ,so,is there a way to catch the possible NullPointerException and continue in the next line of the loop?

Thanks.
 
Ranch Hand
Posts: 456
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i once had a colleague who wrote code like this:

product.getParent().getParent().getParent()...getParent().getName()

he didn't stay long... :-)

you should definitely refactor your method-call chaining to something NPE-safe. not knowing your API, a nested loop would work, but i'm sure you find something more elegant, like getLastChild() or so...

hope it helps,
jan
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You don't want to pepper your drill down with checks for null like this

because it's boring and repetitive. Could you imagine a method that would loop through children on a call like:

See if you can write one like that. And then, as so often happens in my life, say "D'oh! Somebody probably did this already!" and Google for XPATH.
[ April 04, 2006: Message edited by: Stan James ]
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I agree with the other posters. This is a horrible practice. You should always write code that is NPE safe. Not use the try-catch mechanism as just another flow control.

But... As a consultant who has seen code hundreds of times worse than this. And to answer your question...


You can always separate each line with its own try-catch statement.


Henry
 
I have gone to look for myself. If I should return before I get back, keep me here with this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic