ruby – Rescue NameError但不是NoMethodError
发布时间:2020-12-17 03:50:13 所属栏目:百科 来源:网络整理
导读:我需要在特殊情况下捕获NameError.但我不想捕获NameError的所有SubClasses.有没有办法实现这个目标? # This shall be catchedbegin String::NotExistend.newrescue NameError puts 'Will do something with this error'end# This shall not be catchedbegin
我需要在特殊情况下捕获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 解决方法
如果异常的类与给定的不同,则可以重新引发异常:
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |