Forum: Ruby Re: reasons to use else inside rescue

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.
Christopher Dunn (Guest)
on 2006-03-02 05:07
(Received via mailing list)
---
I suppose a difference is that if "do_more_stuff" raises an exception,
the first example can't rescue it and the second might. Is that the
only difference?
---

That's exactly right. The else clause is for code which might issue
exceptions that you would rather not trap.

Note that an "ensure" clause would occur even if an "else" clause
raises an exception, so this:

begin
  do_something
rescue
  handle_exception
else
  do_more_stuff
ensure
  definitely_do_this_last
end


without the "else", would be written like this:

begin
  no_errors = false
  begin
    do_something
    no_errors = true
  rescue
    handle_exception
  do_more_stuff if no_errors
ensure
  definitely_do_this_last
end


Interestingly, Python does not allow except/else with finally. The
reason? It was considered ambiguous to the reader. (In Python2.5, this
constraint is removed.)
This topic is locked and can not be replied to.