Ruby: eval, rescue, and Exception by jgn on Saturday, June 7, 2008 in Ruby and Code

Recently I needed to store bits of Ruby code in the database, and then evaluate them in the context of a particular instance. But one thing I flubbed up was the handling of exceptions. You see, in this situation, if you have bad Ruby code, you will likely raise an exception. My first attempt was, roughly, this code ( wrong! ):

[source language='ruby'] begin eval s rescue # log the fact that s couldn't be eval'ed end [/source]

The catch is that when you use rescue without specify an exception, you are only catching StandardError or one of its subclasses. But eval will raise a SyntaxError (or worse), which is a subclass of ScriptError, which is not a subclass of StandardError. Therefore, you want to rescue an Exception that is further up the hierarchy. In short, better :

[source language='ruby'] begin eval s rescue Exception => e # log the fact that s couldn't be eval'ed end [/source]

Nick Sieger provides a post with the Ruby Exception hierarchy, along with some code to generate it dynamically. Too bad this info isn't in the on-line Pickaxe ( http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_exceptions.html).

comments powered by Disqus