• Post Reply Bookmark Topic Watch Topic
  • New Topic

Resume loop after nullpointerexception  RSS feed

 
Damian Lopez
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • 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.
 
Jan Groth
Ranch Hand
Posts: 456
  • Mark post as helpful
  • send pies
  • 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
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • 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 ]
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • 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
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!