我需要在特殊情况下捕捉一个命名错误。但我不想捕获nameerror的所有子类。有办法做到这一点吗?

# 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

最佳答案

如果异常的类不同于给定的类,则可以重新引发异常:

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

09-26 13:29