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