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