ruby – 在类中的每个方法中添加rescue
发布时间:2020-12-16 21:17:43 所属栏目:百科 来源:网络整理
导读:class A def a_method #.. endendclass B A def method_1 # ... a_method end def method_2 # ... a_method end # ... def method_n # ... a_method endend a_method偶尔会抛出一个AException. 我想从那个例外中解救,比如: class B A def method_1 # ... a_
class A def a_method #.. end end class B < A def method_1 # ... a_method end def method_2 # ... a_method end # ... def method_n # ... a_method end end a_method偶尔会抛出一个AException. 我想从那个例外中解救,比如: class B < A def method_1 # ... a_method rescue AException => e p e.message end # ... end 我想在B类(method_1,method_2,…,method_n)中的每个方法中以相同的方式进行挽救.我坚持找出一个漂亮而干净的解决方案,不需要复制救援代码块.你能帮帮我吗? 解决方法
如何使用块:
class B < A def method_1 # some code here which do not raised an exception with_rescue do # method which raised exception a_method end end def method_2 with_rescue do # ... a_method end end private def with_rescue yield rescue => e ... end end (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |