How to rescue an eval in Ruby? How to rescue an eval in Ruby? ruby ruby

How to rescue an eval in Ruby?


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


Well, that was easy...

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/rubygood_str = "(1+1)"bad_str = "(1+1"    # syntax error: missing closing parenbegin    puts eval(good_str)    puts eval(bad_str)rescue Exception => exc    puts "RESCUED!"end

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:

2RESCUED!