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):
Rescue the File.new exception inside the constructor, and either
throw some class-specific exception or return a class-specific return
Ignore the exception inside the constructor and let the caller catch
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
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: " + $!
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