0

I would like to rescue some code with a custom class in Ruby 2.3 and 2.4. But unlike with the previous versions (such as 2.2 which was working great), I have some troubles. Here an example:

Given this class:

class CustomError < StandardError
end

This code is successfully rescued:

begin
  'foo'.bar(:boom)
rescue
  puts 'THIS IS FINE.'
end

# => printing "THIS IS FINE." on the screen

This one is also successfully rescued:

begin
  'foo'.bar(:boom)
rescue StandardError
  puts 'THIS IS FINE.'
end

# => printing "THIS IS FINE." on the screen

But not this one:

begin
  'foo'.bar(:boom)
rescue CustomError
  puts 'THIS IS FINE.'
end

This message is raised:

undefined method `bar' for "foo":String (NoMethodError)

I don't know why my custom exception class is not handled.

  • 3
    Take a look at the message: a `NoMethodError` was raised, not a `CustomError`. – Stefan Apr 26 '17 at 20:19
  • 1
    BTW, this is _not_ specific to Ruby 2.3 or 2.4. – Stefan Apr 26 '17 at 20:24
  • 1
    It is not specific to 2.3 or 2.4, but it worked with previous versions of Ruby such as 2.1 and 2.2. `NoMethodError` inherits from `StandardError`. And therefore considering Ruby's Exception Hierarchy, it should be rescuable with my `CustomError` class. – Cirus Polis Apr 26 '17 at 20:30
  • 1
    Your conclusion is wrong. Both, `Float` and `Integer` inherit from `Numeric`, but neither `1.is_a?(Float)`, nor `0.5.is_a?(Integer)` is `true`. Same with the exceptions. Just because both inherit from `StandardError` doesn't mean that you can rescue a `NoMethodError` with your `CustomError` (or an `ArgumentError` with an `IndexError`). A `rescue CustomError` will rescue `CustomError` and its subclasses. It won't rescue its ancestors or siblings. – Stefan Apr 26 '17 at 20:50
  • Do you think there is no way to rescue this `NoMethodError` exception using a custom class? – Cirus Polis Apr 26 '17 at 21:01
  • I'm surprised because it worked before. – Cirus Polis Apr 26 '17 at 21:01
  • Why would you want to do that? (and no, it really doesn't work that way in Ruby 2.2 or any other Ruby version) – Stefan Apr 26 '17 at 21:15

1 Answers1

1

You rescue CustomError, but NoMethodError is being raised. NoMethodError inherits StandardError, that's why it can be rescued with rescue StandardError.

sl4vr
  • 81
  • 3