Rescue NameError, but not NoMethodError

I need to catch a NameError in a special case. But I do not want to catch all subclasses of NameError. Is there any 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
+4
source share
3 answers

You can re-create an exception if its class is different from the given one:

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
+3
source

You can also do this in a more traditional way.

begin
  # your code goes here
rescue NoMethodError
  raise
rescue NameError
  puts 'Will do something with this error'
end
+5
source

You can also check the error message and decide what to do. Here is an example of using the code you provided.

# This shall be catched
begin
  String::NotExistend.new
rescue NameError => e 
  if e.message['String::NotExistend'] 
     puts 'Will do something with this error'
   else 
    raise
  end
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 => e 
  if e.message['String::NotExistend'] 
     puts 'Should never be called'
  else
    raise
  end
end
0
source

Source: https://habr.com/ru/post/1651147/


All Articles