Forum: Ruby Ignoring Exceptions

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
2da568aa0fdd279c981eb7412f423a88?d=identicon&s=25 Lin Wj (linwj)
on 2009-02-20 11:13
i am using hpricot to parse xml and place it into an object named 'x'

some_variable = (x.at("some_element_name").innerHTML
                 if x.at("some_element_name"))

problem is i have a TON of"some_element_name" to assign
and i dont want to do a if check for everyone of them

is there anyway to do a straight

some_variable = x.at("some_element_name").innerHTML

and contain them within a begin end and ignore all noMethodExceptions ?
i am ok with having some_variable = null

*noMethodException is raised when i call a .innerHTML method on an
element that doesnt exist.

if i do a rescue exception , it catches it and thats the end of it , it
stops executing.

any ideas ?
76caedd87445c17860358841ae0de620?d=identicon&s=25 Lars Christensen (Guest)
on 2009-02-20 12:15
(Received via mailing list)
On Feb 20, 11:14 am, Lin Wj <mailbox....@gmail.com> wrote:
> some_variable = x.at("some_element_name").innerHTML
>
> any ideas ?

Make a function that does the work for you?

def html_from_element(x, name)
  elem = x.at(name)
  return elem && elem.innerHTML
end
E16e84e861c1815ce11ba7bd851c857d?d=identicon&s=25 lasitha (Guest)
on 2009-02-20 12:19
(Received via mailing list)
On Fri, Feb 20, 2009 at 3:44 PM, Lin Wj <mailbox.lwj@gmail.com> wrote:
> i am using hpricot to parse xml and place it into an object named 'x'
> [... ]
>
> if i do a rescue exception , it catches it and thats the end of it , it
> stops executing.

I don't think there's way to rescue an exception, ignore it and then
continue execution _at the statement following the one that blew up_.

Two alternatives you might consider:

1. Create a method that does the if x.at .. check and call that for
each variable you need assigned.  If you really prefer a rescue over
the check the method could do that instead.

2. How many variables are we talking about ?  I'd consider more than a
handful of them a code 'smell' and think about using a collection.  If
you were looping through a collection then begin/rescue/next would do
what you're talking about above.

Cheers,
lasitha
This topic is locked and can not be replied to.