Search code examples
rubynameerrornomethoderrorrescue

Rescue NameError but not NoMethodError


I need to catch a NameError in a special case. But I don't want to catch all SubClasses of NameError. Is there a way to achieve this?

# This shall be catched
begin
  String::NotExistend.new
rescue NameError
  puts 'Will do something with this error'
end

# This shall not be catched
begin
  # Will raise a NoMethodError but I don't want this Error to be catched
  String.myattribute = 'value'
rescue NameError
  puts 'Should never be called'
end

Solution

  • You can re-raise exception if its class is different than a given:

    begin
      # your code goes here
    rescue NameError => exception
      # note that `exception.kind_of?` will not work as expected here
      raise unless exception.class.eql?(NameError)
    
      # handle `NameError` exception here
    end