Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

exception - How to rescue an eval in Ruby?

I'm trying to figure out how to rescue syntax errors that come up when eval()ing code in Ruby 1.8.6.

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!

Instead, what I get is:

2
eval_rescue.rb:8: (eval):1: compile error (SyntaxError)
(eval):1: syntax error, unexpected $end, expecting ')'

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.

Anybody have any idea how to get the behavior I want (i.e., for my 'rescue' clause to catch the error from the 'eval')?

question from:https://stackoverflow.com/questions/542845/how-to-rescue-an-eval-in-ruby

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Brent already got an answer that works, but I recommend rescuing from the smallest set of exceptions you can get away with. This makes sure you're not accidentally gobbling up something you don't mean to be.

Thus,

begin
  puts eval(good_str)
  puts eval(bad_str)
rescue SyntaxError => se
  puts 'RESCUED!'
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...