rescue clauses on Ruby class and module definitions

I've been studying exceptions in Ruby, and have discovered some syntax that is not documented in the Pickaxe, nor anywhere obvious that I can find with Google.

Everyone knows about rescue clauses with begin/end. And most Ruby programmers probably know that you can use a rescue clause at the end of a method definition. What I was surprised to discover (by reading the parse.y grammar file in the source distribution) is that rescue clauses are also allowed at the end of class and module definitions.

This, for example, is legal Ruby:

class Test
  def t
    1
  end
  raise "foo"
rescue 
  p $!
else
  p "Class Test defined without exceptions"
ensure
  p "Exiting class Test"
end

p Test.new.t

I'm not sure when this would be useful, but it is legal, and it ought to be documented!

Books

Comprehensive coverage of Ruby 1.8 and 1.9

"The New Most Important Ruby Book"
Peter Cooper,
rubyinside.com

Completely updated for Ajax and Web 2.0

"A must-have reference"
Brendan Eich,
creator of JavaScript

The classic Java quick-reference

Advertising

Pages

Hosted By

Powered by Movable Type 4.21-en