Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 437
PascalTurbo Avatar asked Jan 06 '23 13:01

PascalTurbo


1 Answers

You can also do it in a more traditional way

begin
  # your code goes here
rescue NoMethodError
  raise
rescue NameError
  puts 'Will do something with this error'
end
like image 77
Aetherus Avatar answered Jan 14 '23 06:01

Aetherus