If you ran the ensure.rb program earlier and you were watching closely, you may have noticed something unusual when you tried to log onto a nonexistent drive (for example, on my system that might be the X: drive). Often, when an exception occurs, the exception class is an instance of a specific named type such as ZeroDivisionError or NoMethodError. In this case, however, the class of the exception is shown to be Errno::ENOENT
.
It turns out that there is quite a variety of Errno
errors in Ruby. Try disk_err.rb. This defines a method, chDisk
, which attempts to log onto a disk identified by the character, aChar
. So if you pass “A” as an argument to chDisk
, it will try to log onto the A: drive. I’ve called the chDisk
method three times, passing to it a different string each time:
disk_err.rb
def chDisk( aChar ) startdir = Dir.getwd begin Dir.chdir( "#{aChar}:\" ) puts( `dir` ) rescue Exception => e #showFamily( e.class ) # to see ancestors, uncomment puts e.class # ...and comment out this puts e ensure Dir.chdir( startdir ) end end chDisk( "F" ) chDisk( "X" ) chDisk( "ABC" )
You might, of course, need to edit the paths to something different on your computer. On my PC, F: is my DVD drive. At the moment, it is empty, and when my program tries to log onto it, Ruby returns an exception of this type: Errno::EACCES
.
I have no X: drive on my PC, and when I try to log onto that, Ruby returns an exception of this type: Errno::ENOENT
.
In the previous example, I pass the string parameter “ABC,” which is invalid as a disk identifier, and Ruby returns an exception of this type: Errno::EINVAL
.
Errors of this type are descendants of the SystemCallError class. You can easily verify this by uncommenting the line of code to show the class’s family where indicated in the source code of disk_err.rb. This calls the same showFamily
method, which you used earlier in the exception_tree.rb program.
These Error classes, in effect, wrap up integer error values that are returned by the underlying operating system. Both the names and the values of constants may vary according to the operating system and the version of Ruby. Here Errno
is the name of the module containing the constants, such as EACCES
and ENOENT
, which match the integer error values.
To see a complete list of Errno
constants, run this:
errno.rb
puts( Errno.constants )
To view the corresponding numerical value of any given constant, append ::Errno
to the constant name, like this:
Errno::EINVAL::Errno
You can use the following code to display a list of all Errno
constants along with their numerical values (here the eval
method evaluates the expression passed to it—you’ll look at how this works in Chapter 20):
for err in Errno.constants do errnum = eval( "Errno::#{err}::Errno" ) puts( "#{err}, #{errnum}" ) end
18.117.189.228