I have some code that needs to rescue multiple types of exceptions in ruby:
begin
a = rand
if a > 0.5
raise FooException
else
raise BarException
end
rescue FooException, BarException
puts "rescued!"
end
What I'd like to do is somehow store the list of exception types that I want to rescue somewhere and pass those types to the rescue clause:
EXCEPTIONS = [FooException, BarException]
and then:
rescue EXCEPTIONS
Is this even possible, and is it possible without some really hack-y calls to eval
? I'm not hopeful given that I'm seeing TypeError: class or module required for rescue clause
when I attempt the above.
You can use an array with the splat operator
*
.If you are going to use a constant for the array as above (with
EXCEPTIONS
), note that you cannot define it within a definition, and also if you define it in some other class, you have to refer to it with its namespace. Actually, it does not have to be a constant.Splat Operator
The splat operator
*
"unpacks" an array in its position so thatmeans the same as
You can also use it within an array literal as
which is the same as
or in an argument position
which means
[]
expands to vacuity:One difference between ruby 1.8 and ruby 1.9 is with
nil
.Be careful with objects on which
to_a
is defined, asto_a
will be applied in such cases:With other types of objects, it returns itself.
While the answer given by @sawa is technically right, I think it misuses Ruby's exception handling mechanism.
As the comment by Peter Ehrlich suggests (by pointing to an old blog post by Mike Ferrier), Ruby is already equipped with a DRY exception handler mechanism:
By using this technique, we can access the exception object, which usually has some valuable information in it.
I just ran into this issue and found an alternate solution. In the case your
FooException
andBarException
are all going to be custom exception classes and particularly if they are all thematically related, you can structure your inheritance hierarchy such that they will all inherit from the same parent class and then rescue only the parent class.For example I had three exceptions:
FileNamesMissingError
,InputFileMissingError
, andOutputDirectoryError
that I wanted to rescue with one statement. I made another exception class calledFileLoadError
and then set up the above three exceptions to inherit from it. I then rescued onlyFileLoadError
.Like this: