如何在Ruby中挽救评估? [英] How to rescue an eval in Ruby?
问题描述
我试图弄清楚在Ruby 1.8.6中 eval()
代码时出现的语法错误。
I'm trying to figure out how to rescue syntax errors that come up when eval()
ing code in Ruby 1.8.6.
我期望下面的Ruby代码:
I would expect the following Ruby code:
#!/usr/bin/ruby
good_str = "(1+1)"
bad_str = "(1+1" # syntax error: missing closing paren
begin
puts eval(good_str)
puts eval(bad_str)
rescue => exc
puts "RESCUED!"
end
在运行时产生以下结果:
to produce the following result when run:
2
RESCUED!
相反,我得到的是:
2
eval_rescue.rb:8: (eval):1: compile error (SyntaxError)
(eval):1: syntax error, unexpected $end, expecting ')'
看来,eval方法引发的SyntaxError正在被救出。评估,而没有给我自己处理的机会。
It appears that the SyntaxError raised by the eval method is being rescued somewhere within the eval, without giving me a chance to handle it myself.
任何人都不知道如何处理以及我想要的行为(即,为了使我的'rescue'子句捕捉'eval'中的错误)?
Anybody have any idea how to get the behavior I want (i.e., for my 'rescue' clause to catch the error from the 'eval')?
推荐答案
好吧,这很容易...
Well, that was easy...
事实证明,默认情况下, rescue语句不会捕获所有异常,但是仅那些是StandardError子类的对象。 SyntaxError是StandardError的同级/表兄弟,而不是它的子类,因此,除非明确告知,否则save语句不会捕获它。
It turns out that, by default, the "rescue" statement does not catch all exceptions, but only those that are subclasses of StandardError. SyntaxError is a sibling/cousin of StandardError, not a subclass of it, so the rescue statement doesn't capture it unless explicitly told to.
要捕获急救块所有例外,您需要将代码更改为以下内容:
To have the rescue block capture all exceptions, you need to change the code to the following:
#!/usr/bin/ruby
good_str = "(1+1)"
bad_str = "(1+1" # syntax error: missing closing paren
begin
puts eval(good_str)
puts eval(bad_str)
rescue Exception => exc
puts "RESCUED!"
end
请注意救援行中的变化,从 rescue => exc变为 rescue Exception => exc。
Note the change in the "rescue" line, from "rescue => exc" to "rescue Exception => exc".
现在,在运行代码时,您将获得所需的结果:
Now, when you run the code, you get the desired results:
2
RESCUED!
这篇关于如何在Ruby中挽救评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!