2016-08-13 60 views
4

我需要在特殊情況下捕獲NameError。但我不想捕獲NameError的所有子類。有沒有辦法做到這一點?Rescue NameError但不是NoMethodError

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

如果同級車比一個給定的不同您可以重新引發異常例外信息並決定要做什麼。 以下是使用您提供的代碼的示例。

# 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

此解決方案符合我的需求。 – PascalTurbo

4

你也可以做一個更傳統的方式

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

它現在或將來只能與'NoMethodError'一起使用,而不能與其他的子類一起使用。 – smefju

0

您還可以查看:

# 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 
+0

如果會出現'String :: NotExistend2'會怎麼樣?最好是檢查異常的類,而不是在http://stackoverflow.com/a/38931436/1941418 – smefju

+1

回答我猜這取決於你所有的「特殊」情況是什麼。我的答案的重點是,您可以使用該消息過濾出特定例外的特定信息。如果僅僅檢查課程涵蓋了所有特殊情況而不是使用它,如果沒有,您還有其他選擇 – nPn