I'm trying to understand exceptions in Ruby but I'm a little confused. The tutorial I'm using says that if an exception occurs that does not match any of the exceptions identified by the rescue statements, you can use an "else" to catch it:
begin
# -
rescue OneTypeOfException
# -
rescue AnotherTypeOfException
# -
else
# Other exceptions
ensure
# Always will be executed
end
However, I also saw later in the tutorial "rescue" being used without an exception specified:
begin
file = open("/unexistant_file")
if file
puts "File opened successfully"
end
rescue
file = STDIN
end
print file, "==", STDIN, "\n"
If you can do this, then do I ever need to use else? Or can I just use a generic rescue at the end like this?
begin
# -
rescue OneTypeOfException
# -
rescue AnotherTypeOfException
# -
rescue
# Other exceptions
ensure
# Always will be executed
end
elseclause inside abeginblock is used to rescue errors of a type not specified in the preceedingrescueclauses (Basically the same that the tutorial from this question said). That is incorrect. It confused me for a while - gascbegin/endblock, theelseblock is only run when there are NO exceptions raised. It is NOT a catch-all for "any other" exception. The need forelseis pretty rare...typically you'd just put your ongoing, non-exception, code in the mainbeginblock, before any rescues. See later answers for some legit esoteric uses ofelse. - David Hempy