Propagating exceptions from File.new

Hello,

Suppose I have a class with a constructor that accepts a configuration
file (in XML format). Part of an object’s initialization is to read some
data from the XML file.

However, sometimes the file passed into the constructor doesn’t exist,
and I wonder about the best idiomatic way in Ruby to handle it.

There are two main approaches (using File.new to open the file):

  1. Rescue the File.new exception inside the constructor, and either
    throw some class-specific exception or return a class-specific return
    code

  2. Ignore the exception inside the constructor and let the caller catch
    it

Approach (2) looks cleaner, but leads me to wonder how to document the
exceptions my class is throwing (in C++ there’s a useful construct for
this), can this only be done by means of non-code documentation (a
comment) ?. Moreover, trying to test this solution, I got stuck in
finding out which exception File.new actually throws when it doesn’t
find a file. It says:

test.rb:12:in `initialize’: No such file or directory - test.rbgt
(Errno::ENOENT)

Trying to rescue IOError doesn’t work, what does ? (except for the
general catch-all ‘rescue Exception’, of course)

rescue Exception => details
puts "IO Failed: " + $!
p details.class
end

the second print prints: “Errno::ENOENT” - is this a kind of exception ?

How can I find out which exceptions are actually thrown by standard Ruby
classes, without looking at the source code or deciphering them with
.class ?

Eli B. wrote:

> How can I find out which exceptions are actually thrown by standard Ruby > classes, without looking at the source code or deciphering them with > .class ?

Any ideas about this ?

On 06/05/06, Eli B. [email protected] wrote:

Hello,
[…]
the second print prints: “Errno::ENOENT” - is this a kind of exception ?

Yes: Errno::ENOENT < SystemCallError < StandardError < Exception

How can I find out which exceptions are actually thrown by standard Ruby
classes, without looking at the source code or deciphering them with
.class ?

Well, you said it. Look up in the sources and (maybe) documentation or
collect some empirical evidence. Note that what exceptions descend
from SystemCallErrors depends on the OS, and are a subset of those
defined in sys/errno.h.

Ciao,
Stefano