Ruby 捕获 NoMethodError 并从发生异常的地方继续执行
在 Ruby 中,我想在另一个对象中捕获一个对象上生成的 NoMethodError,然后将一些值返回到引发异常的位置并继续执行。有现有的方法可以做到这一点吗?
我想出的最好的办法是:
class Exception
attr_accessor :continuation
end
class Outer
def hello
puts "hello"
end
class Inner
def world
puts "world"
end
def method_missing(method, *args, &block)
x = callcc do |cc|
e = RuntimeError.exception(method)
e.continuation = cc
raise e
end
return x
end
end
def inner(&block)
inner = Inner.new
begin
inner.instance_eval(&block)
rescue => e
cc = e.continuation
cc.call(hello())
end
inner
end
end
o = Outer.new
o.inner do
hello
world
end
这会打印
hello
world
Is there a better way to do this using Ruby's Existing array of meta-programming arsenal?基本上,我不确定callcc是否会继续存在。
谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个简单的方法怎么样:
Will print
在这种情况下,如果内部类没有定义所需的方法,它会使用 对象#send。当
Outer
类没有定义委托方法时,您可以在method_missing
内部捕获NoMethodError
,以控制情况。更新
还可以使用光纤来解决问题:
What about this simple approach:
Will print
In this case if inner class does not define required method it delegate it to the outer class using Object#send. You can catch
NoMethodError
insidemethod_missing
in order to control situation whenOuter
class does not define delegated method.UPDATE
You can also use fibers to solve the problem:
Ruby 有一个名为
throw
的关键字,可用于向上传播错误。我无法从您的帖子中真正看出您想要在哪个块中执行此操作,但它是这样的:在 throw 语句和 catch 块执行
some_method
中的剩余语句之后应该执行希望这会有所帮助
Ruby has a keyword called
throw
that can be used to propagate errors upward. I can't really tell from your post which block you would want this in but it goes something like this:After the throw statement and catch block execute the remaining statements in
some_method
should executeHope this helps