Rescue NameError但不是NoMethodError

时间:2016-08-13 09:14:28

标签: ruby nameerror nomethoderror rescue

我需要在特殊情况下捕获NameError。但我不想捕获NameError的所有SubClasses。有没有办法实现这个目标?

# 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

3 个答案:

答案 0 :(得分:6)

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

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

答案 1 :(得分:3)

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

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

答案 2 :(得分:0)

您还可以检查异常消息并确定要执行的操作。 以下是使用您提供的代码的示例。

# 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