拯救 NameError 而不是 NoMethodError

Rescue NameError but not NoMethodError

我需要在特殊情况下捕获 NameError。但我不想捕获 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

如果 class 与给定的不同,您可以重新引发异常:

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

你也可以用更传统的方式来做

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

您还可以查看异常消息并决定要做什么。 这是使用您提供的代码的示例。

# 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