Forum: Ruby propagating exceptions from File.new

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Fc761ccaf6c0d7d977e2959f9bfebd06?d=identicon&s=25 Eli Bendersky (eliben)
on 2006-05-06 16:33
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 ?
Fc761ccaf6c0d7d977e2959f9bfebd06?d=identicon&s=25 Eli Bendersky (eliben)
on 2006-05-08 17:45
Eli Bendersky wrote:

<snip>
> 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 ?
893c38bd5f182afc751540657d8aacf7?d=identicon&s=25 Stefano Taschini (Guest)
on 2006-05-08 20:02
(Received via mailing list)
On 06/05/06, Eli Bendersky <eliben@gmail.com> 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
This topic is locked and can not be replied to.