Mike Ferrier

I beat code into submission.

Rescuing Multiple Exception Types in Ruby and Binding to Local Variable

Took me a few minutes to figure this out and wasn’t easy to Google, so hopefully this helps someone out.

Rescuing multiple exceptions in one rescue clause is pretty intuitive:

1
2
3
4
5
begin
  rand(2) == 0 ? ([] + '') : (foo)
rescue TypeError, NameError
  puts "oops"
end

I wanted to also bind the exception, whatever it is, to a local variable. To do that for a single exception is like:

1
2
3
4
5
begin
  [] + ''
rescue TypeError => e
  puts "oops: #{e.message}"
end

To combine the two, list the exceptions and then name the local variable with the last type in the list:

1
2
3
4
5
begin
  rand(2) == 0 ? ([] + '') : (foo)
rescue TypeError, NameError => e
  puts "oops: #{e.message}"
end

Comments