Q: will this always work: rescuing with non-Exception classes

I wondered whether the clause rescue would accept any modules, not
just exception classes. Well, at least in MRI 1.8.7, it does (example
appended). But will this work in all Ruby implementations?

Regards,

Jeremy H.

Example (prints “Rescued!”)

module MyModule
end

class MyException < StandardError
  include MyModule
end

begin
  raise MyException
rescue MyModule
  puts 'Rescued!'
end

On Feb 13, 6:45 pm, Jeremy H. [email protected] wrote:

module MyModule
end

That’s interesting. If it is using #=== to determine this then it
should.

Interesting idea. Seems to work pretty much everywhere.

~ ✖ ruby-1.9.1-p378 ▸ rvm ruby test.rb

macruby-nightly: MacRuby version 0.6 (ruby 1.9.0) [universal-
darwin10.0, x86_64]

Rescued!

mput-head: ruby 1.9.2dev (2010-02-14 trunk 26661) [x86_64-
darwin10.2.0]

Rescued!

rbx-1.0.0-rc2: rubinius 1.0.0-rc2 (1.8.7 release 2010-01-04 JI)
[x86_64-apple-darwin10.2.0]

Rescued!

ree-1.8.7-2009.10: ruby 1.8.7 (2009-06-12 patchlevel 174) [i686- darwin10.2.0], MBARI 0x6770, Ruby Enterprise Edition 2009.10

Rescued!

ruby-1.8.7-p248: ruby 1.8.7 (2009-12-24 patchlevel 248) [i686- darwin10.2.0]

Rescued!

ruby-1.9.1-p378: ruby 1.9.1p378 (2010-01-10 revision 26273) [i386- darwin10.2.0]

Rescued!
~ ✖ ruby-1.9.1-p378 ▸

(Following up to myself to summarise)

On 2010-02-13, Jeremy H. [email protected] wrote:

I wondered whether the clause rescue would accept any modules, not
just exception classes. Well, at least in MRI 1.8.7, it does
(example appended). But will this work in all Ruby implementations?

As reported elsewhere in the thread, this does seem to work
everywhere.

MRI 1.8.7 raises “class or module required for rescue clause
(TypeError)” if the handler is not a module. It tests whether the
exception matches the handler with ::=== (I checked this by
redefining self.#=== inside a module).

“Programming Ruby” (2nd ed.) explicitly says that the match test uses
#=== . Its language implicitly presumes (at least as I read it) that
the handlers should be Exception classes, not arbitrary modules.

The Draft Ruby Specification 20091201 disagrees with everyone! It
says that a TypeError is raised if the handler is not an Exception
class. Furthermore it says that the exception is handled if it is an
instance of the handler, rather than if it satisfies ::=== .
This rather goes against the specification’s stated intent that
existing implementations should conform without modification.

Regards,

Jeremy H.