Re: reasons to use else inside rescue


#1

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.)