begin/rescue not behaving how I want

J

J. Cooper

So I have some code that routinely checks for email in a cron job. Most
of the time it works great. However, sometimes it gets a timeout error,
which is fine; it happens. The thing is, I don't want it to clog up my
logs when it does, because it's not an exception I'm worried about. So I
tried wrapping the code in question in a begin/rescue block that just
exits on exception, thinking that then it the error would be "caught"
and it wouldn't have to bug me about it... but it continues to do so.
How do I get what I want to achieve here?

(The relevant code, if needed):
begin
Net::pOP3.start('foo', 110, 'bar', 'foobar') do |pop|
if pop.mails.empty?
exit
else
# blah blah etc.
end
end
rescue
exit
end
 
J

J. Cooper

Oh, and thanks of course!!

(Didn't mean to be rude; got distracted pasting code)
 
A

Arlen Cuss

[Note: parts of this message were removed to make it a legal post.]

Check out these two cases:

celtic@sohma:~$ irb(irb):2:in `irb_binding': data (Timeout::Error)
from /usr/lib/ruby/1.8/irb/workspace.rb:52:in `irb_binding'
from /usr/lib/ruby/1.8/irb/workspace.rb:52

celtic@sohma:~$ irbError with data.
=> nil
In the first one, the exception is raised (and irb doesn't catch it and
dies). In the second one, we explicitly catch TimeoutError, and it's fine.
Why so?

TimeoutError isn't a "StandardError", which is the default thing that
`rescue' tries to rescue when you leave it blank!

Notice that it goes TimeoutError < Interrupt < SignalException < Exception.
Whereas, for example...

A ZeroDivisionError is of superclass StandardError (which is then an
Exception). So it would get caught.

To catch all cases, try rescue Exception -- or REALLY all cases with rescue
Object. (if you're crazy.) But of course, try not to catch anything you're
not expecting - that's how unexpected errors turn up. Instead, perhaps just
rescue Timeout (if it's the only error you expect). That way other errors
you don't expect aren't silently thrown away [leading to frustration for you
when you try to debug!]

Cheers,
Arlen.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top