Ruby: eval, rescue, and Exception
Jun/080
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!):
begin eval s rescue # log the fact that s couldn't be eval'ed end
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:
begin eval s rescue Exception => e # log the fact that s couldn't be eval'ed end
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).
No comments yet.
Leave a comment
No trackbacks yet.
