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
.
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
.
To see a complete list of Errno
constants, run this:
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