<ppdoc>
<copyright>
    Copyright (c) 2001 by Addison Wesley Longman.  This
    material may be distributed only subject to the terms and
    conditions set forth in the Open Publication License, v1.0 or
    later (the latest version is presently available at
    http://www.opencontent.org/openpub/).
</copyright>
<chapter  ref="xref-000001" name="Exceptions, Catch, and Throw">
<p/>
So far we're been developing code in Pleasantville, a wonderful
place where nothing ever, ever goes wrong.
Every library call
succeeds, users never enter incorrect data, and resources are
plentiful and cheap.  Well, that's about to change. Welcome to the
real world!
<p/>
In the real world, errors happen. Good programs (and programmers)
anticipate them and arrange to handle them gracefully. This isn't
always as easy as it might be. Often the code that detects an error
does not have the context to know what to do about it. For example,
attempting to open a file that doesn't exist is acceptable in some
circumstances and is a fatal error at other times. What's your
file-handling module to do?
<p/>
The traditional approach is to use return codes. The <meth>open</meth>
method returns some specific value to say it failed. This value
is then propagated back through the layers of calling routines
until someone wants to take responsibility for it.
<p/>
The problem with this approach is that managing all these error codes
can be a pain. If a function calls <meth>open</meth>, then <meth>read</meth>,
and finally <meth>close</meth>, and each can return an error indication, how
can the function distinguish these error codes in the value it returns
to <em>its</em> caller?
<p/>
To a large extent, exceptions solve this problem. Exceptions let you
package up information about an error into an object. That exception
object is then propagated back up the calling stack automatically
until the runtime system finds code that explicitly declares that it
knows how to handle that type of exception.
<section>The Exception Class</section>
<p/>
The package that contains the information about an exception is an
object of class <classname>Exception</classname>, or one of class <classname>Exception</classname>'s
children. Ruby predefines a tidy hierarchy of exceptions, shown in
Figure 8.1 on page 91. As we'll see later, this hierarchy
makes handling exceptions considerably easier.
<p/>
<figure type="figure">Figure not available...</figure>
<p/>
When you need to raise an exception, you can use one of the built-in
<classname>Exception</classname> classes, or you can create one of your own. If you
create your own, you might want to make it a subclass of
<exception>StandardError</exception> or one of its children. If you don't, your exception
won't be caught by default.
<p/>
Every <classname>Exception</classname> has associated with it a message string and a
stack backtrace. If you define your own exceptions, you can add
additional information.
<section>Handling Exceptions</section>
<p/>
Our jukebox downloads songs from the Internet using a TCP socket. The
basic code is simple:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  opFile = File.open(opName, "w")
  while data = socket.read(512)
    opFile.write(data)
  end
]]></fullcode>
opFile<nbsp/>=<nbsp/>File.open(opName,<nbsp/>"w")
while<nbsp/>data<nbsp/>=<nbsp/>socket.read(512)
<nbsp/><nbsp/>opFile.write(data)
end
</alltt>
</codefragment>
<p/>
What happens if we get a fatal error halfway through the download? We
certainly don't want to store an incomplete song in the song list.
``I Did It My *click*''.
<p/>
Let's add some exception handling code and see how it helps.
We
enclose the code that could raise an exception in a
<kw>begin</kw>/<kw>end</kw> block and use <kw>rescue</kw> clauses to tell Ruby the
types of exceptions we want to handle. In this case we're interested
in trapping <classname>SystemCallError</classname> exceptions (and, by implication, any
exceptions that are subclasses of <classname>SystemCallError</classname>), so that's what
appears on the <kw>rescue</kw> line.  In the error handling block, we
report the error, close and delete the output file, and then reraise
the exception.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  opName = "/tmp/testfile"
!-  socket = $stdin
  opFile = File.open(opName, "w")
  begin
    # Exceptions raised by this code will
    # be caught by the following rescue clause
    while data = socket.read(512)
      opFile.write(data)
    end

  rescue SystemCallError
    $stderr.print "IO failed: " + $!
    opFile.close
    File.delete(opName)
    raise
  end
]]></fullcode>
opFile<nbsp/>=<nbsp/>File.open(opName,<nbsp/>"w")
begin
<nbsp/><nbsp/>#<nbsp/>Exceptions<nbsp/>raised<nbsp/>by<nbsp/>this<nbsp/>code<nbsp/>will
<nbsp/><nbsp/>#<nbsp/>be<nbsp/>caught<nbsp/>by<nbsp/>the<nbsp/>following<nbsp/>rescue<nbsp/>clause
<nbsp/><nbsp/>while<nbsp/>data<nbsp/>=<nbsp/>socket.read(512)
<nbsp/><nbsp/><nbsp/><nbsp/>opFile.write(data)
<nbsp/><nbsp/>end
<p/>
rescue<nbsp/>SystemCallError
<nbsp/><nbsp/>$stderr.print<nbsp/>"IO<nbsp/>failed:<nbsp/>"<nbsp/>+<nbsp/>$!
<nbsp/><nbsp/>opFile.close
<nbsp/><nbsp/>File.delete(opName)
<nbsp/><nbsp/>raise
end
</alltt>
</codefragment>
<p/>
When an exception is raised, and independent of any subsequent
exception handling, Ruby places a reference to the <exception>Exception</exception>
object associated with the exception in the global variable <var>$!</var>
(the exclamation point presumably mirroring our surprise that any of
<em>our</em> code could cause errors). In the previous example, we used
this variable to format our error message.
<p/>
After closing and deleting the file, we call <meth>raise</meth> with no
parameters, which reraises the exception in <var>$!</var>. This is a
useful technique, as it allows you to write code that filters
exceptions, passing on those you can't handle to higher levels.  It's
almost like implementing an inheritance hierarchy for error
processing.
<p/>
You can have multiple <kw>rescue</kw> clauses in a <kw>begin</kw> block, and
each <kw>rescue</kw> clause can specify multiple exceptions to catch.  At
the end of each rescue clause you can give Ruby the name of a local
variable to receive the matched exception. Many people find this more
readable than using <var>$!</var> all over the place.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-string = "1"
  begin
    eval string
  rescue SyntaxError, NameError => boom
    print "String doesn't compile: " + boom
  rescue StandardError => bang
    print "Error running script: " + bang
  end
]]></fullcode>
begin
<nbsp/><nbsp/>eval<nbsp/>string
rescue<nbsp/>SyntaxError,<nbsp/>NameError<nbsp/>=&gt;<nbsp/>boom
<nbsp/><nbsp/>print<nbsp/>"String<nbsp/>doesn't<nbsp/>compile:<nbsp/>"<nbsp/>+<nbsp/>boom
rescue<nbsp/>StandardError<nbsp/>=&gt;<nbsp/>bang
<nbsp/><nbsp/>print<nbsp/>"Error<nbsp/>running<nbsp/>script:<nbsp/>"<nbsp/>+<nbsp/>bang
end
</alltt>
</codefragment>
<p/>
How does Ruby decide which rescue clause to execute? It turns out that
the processing is pretty similar to that used by the <kw>case</kw>
statement. For each <kw>rescue</kw> clause in the <kw>begin</kw> block, Ruby
compares the raised exception against each of the parameters in turn.
If the raised exception matches a parameter, Ruby executes the body of
the <kw>rescue</kw> and stops looking. The match is made using
<tt>$!.kind_of?(<em>parameter</em>)</tt>, and so will succeed if the parameter
has the same class as the exception or is an ancestor of the
exception.  If you write a <kw>rescue</kw> clause with no parameter list,
the parameter defaults to <exception>StandardError</exception>.
<p/>
If no <tt>rescue</tt> clause matches, or if an exception is raised outside
a <tt>begin</tt>/<tt>end</tt> block, Ruby moves up the stack
and looks for an
exception handler in the caller, then in the caller's caller, and so on.
<p/>
Although the parameters to the <kw>rescue</kw> clause are typically the
names of <exception>Exception</exception> classes, they can actually be arbitrary
expressions (including method calls) that return an <classname>Exception</classname> class.
<subsection>Tidying Up</subsection>
<p/>
Sometimes you need to guarantee that some processing is done at the
end of a block of code, regardless of whether an exception was raised.
For example, you may have a file open on entry to the block, and you
need to make sure it gets closed as the block exits.
<p/>
The <kw>ensure</kw> clause does just this.
<kw>ensure</kw> goes after the last 
<kw>rescue</kw> clause and contains a chunk of code that will always be
executed as the block terminates. It doesn't matter if the block exits 
normally, if it raises and rescues an exception, or if it is terminated
by an uncaught exception---the <kw>ensure</kw> block will get run.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  f = File.open("testfile")
  begin
    # .. process
  rescue
    # .. handle error
  ensure
    f.close unless f.nil?
  end
]]></fullcode>
f<nbsp/>=<nbsp/>File.open("testfile")
begin
<nbsp/><nbsp/>#<nbsp/>..<nbsp/>process
rescue
<nbsp/><nbsp/>#<nbsp/>..<nbsp/>handle<nbsp/>error
ensure
<nbsp/><nbsp/>f.close<nbsp/>unless<nbsp/>f.nil?
end
</alltt>
</codefragment>
<p/>
The <kw>else</kw>
clause is a similar, although less useful, construct. If 
present, it goes after the <kw>rescue</kw> clauses and before any
<kw>ensure</kw>. The body of an <kw>else</kw> clause is executed only if no
exceptions are raised by the main body of code.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  f = File.open("testfile")
  begin
    # .. process
  rescue
    # .. handle error
  else
    puts "Congratulations-- no errors!"
  ensure
    f.close unless f.nil?
  end
]]></fullcode>
f<nbsp/>=<nbsp/>File.open("testfile")
begin
<nbsp/><nbsp/>#<nbsp/>..<nbsp/>process
rescue
<nbsp/><nbsp/>#<nbsp/>..<nbsp/>handle<nbsp/>error
else
<nbsp/><nbsp/>puts<nbsp/>"Congratulations--<nbsp/>no<nbsp/>errors!"
ensure
<nbsp/><nbsp/>f.close<nbsp/>unless<nbsp/>f.nil?
end
</alltt>
</codefragment>
<subsection>Play It Again</subsection>
<p/>
Sometimes you may be able to correct the cause of an exception. In
those cases, you can use the <kw>retry</kw> statement within a <kw>rescue</kw>
clause to repeat the entire <kw>begin</kw>/<kw>end</kw> block.
Clearly there
is tremendous scope for infinite loops here, so this is a feature to
use with caution (and with a finger resting lightly on the interrupt
key).
<p/>
As an example of code that retries on exceptions, have a look at the
following, adapted from Minero Aoki's <tt>net/smtp.rb</tt> library.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  @esmtp = true
  
  begin
    # First try an extended login. If it fails because the
    # server doesn't support it, fall back to a normal login
    
    if @esmtp then
      @command.ehlo(helodom)
    else
      @command.helo(helodom)
    end
    
  rescue ProtocolError
    if @esmtp then
      @esmtp = false
      retry
    else
      raise
    end
  end
]]></fullcode>
@esmtp<nbsp/>=<nbsp/>true
<p/>
begin
<nbsp/><nbsp/>#<nbsp/>First<nbsp/>try<nbsp/>an<nbsp/>extended<nbsp/>login.<nbsp/>If<nbsp/>it<nbsp/>fails<nbsp/>because<nbsp/>the
<nbsp/><nbsp/>#<nbsp/>server<nbsp/>doesn't<nbsp/>support<nbsp/>it,<nbsp/>fall<nbsp/>back<nbsp/>to<nbsp/>a<nbsp/>normal<nbsp/>login
<p/>
<nbsp/><nbsp/>if<nbsp/>@esmtp<nbsp/>then
<nbsp/><nbsp/><nbsp/><nbsp/>@command.ehlo(helodom)
<nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/>@command.helo(helodom)
<nbsp/><nbsp/>end
<p/>
rescue<nbsp/>ProtocolError
<nbsp/><nbsp/>if<nbsp/>@esmtp<nbsp/>then
<nbsp/><nbsp/><nbsp/><nbsp/>@esmtp<nbsp/>=<nbsp/>false
<nbsp/><nbsp/><nbsp/><nbsp/>retry
<nbsp/><nbsp/>else
<nbsp/><nbsp/><nbsp/><nbsp/>raise
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
This code tries first to connect to an SMTP server using the <tt>EHLO</tt> 
command, which is not universally supported. If the connection attempt
fails, the code sets the <var>@esmtp</var> variable to <const>false</const> and
retries the connection. If this fails again, the exception is reraised 
up to the caller.
<section>Raising Exceptions</section>
<p/>
So far we've been on the defensive, handling exceptions raised by
others.
It's time to turn the tables and go on the offensive. (There
are those that say your gentle authors are always offensive, but
that's a different book.)
<p/>
You can raise exceptions in your code with the <mmm><file>kernel</file><front>Kernel</front><back>raise</back><mref>raise</mref></mmm>
method.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[raise
raise "bad mp3 encoding"
raise InterfaceException, "Keyboard failure", caller
]]></fullcode>
raise
raise<nbsp/>"bad<nbsp/>mp3<nbsp/>encoding"
raise<nbsp/>InterfaceException,<nbsp/>"Keyboard<nbsp/>failure",<nbsp/>caller
</alltt>
</codefragment>
<p/>
The first form simply reraises the current exception (or a
<exception>RuntimeError</exception> if there is no current exception). This is used in 
exception handlers that need to intercept an exception before passing
it on.
<p/>
The second form creates a new <exception>RuntimeError</exception> exception, setting its 
message to the given string. This exception is then raised up the call 
stack.
<p/>
The third form uses the first argument to create an exception and then
sets the associated message to the second argument and the stack
trace to the third argument. Typically the first argument will be either the
name of a class in the <exception>Exception</exception> hierarchy or a reference to an
object instance of one of these classes.<footnote>Technically, this
  argument can be any object that responds to the message
  <meth>exception</meth> by returning an object such that
  <tt>object.kind_of?(Exception)</tt> is true.</footnote> The stack trace is
normally produced using the <mmm><file>kernel</file><front>Kernel</front><back>caller</back><mref>caller</mref></mmm> method.
<p/>
Here are some typical examples of <meth>raise</meth> in action.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  raise

  raise "Missing name" if name.nil?

  if i >= myNames.size
    raise IndexError, "#{i} >= size (#{myNames.size})"
  end

  raise ArgumentError, "Name too big", caller
]]></fullcode>
raise
<p/>
raise<nbsp/>"Missing<nbsp/>name"<nbsp/>if<nbsp/>name.nil?
<p/>
if<nbsp/>i<nbsp/>&gt;=<nbsp/>myNames.size
<nbsp/><nbsp/>raise<nbsp/>IndexError,<nbsp/>"#{i}<nbsp/>&gt;=<nbsp/>size<nbsp/>(#{myNames.size})"
end
<p/>
raise<nbsp/>ArgumentError,<nbsp/>"Name<nbsp/>too<nbsp/>big",<nbsp/>caller
</alltt>
</codefragment>
<p/>
In the last example, we remove the current routine from the stack
backtrace, which is often useful in library modules. We can take this
further: the following code removes two routines from the backtrace.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  raise ArgumentError, "Name too big", caller[1..-1]
]]></fullcode>
raise<nbsp/>ArgumentError,<nbsp/>"Name<nbsp/>too<nbsp/>big",<nbsp/>caller[1..-1]
</alltt>
</codefragment>
<subsection>Adding Information to Exceptions</subsection>
<p/>
You can define your own exceptions to hold any information that you
need to pass out from the site of an error. For example, certain types 
of network errors might be transient depending on the circumstances.
If such an error occurs, and the circumstances are right, you could
set a flag in the exception to tell the handler that it might be worth 
retrying the operation.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  class RetryException < RuntimeError
    attr :okToRetry
    def initialize(okToRetry)
      @okToRetry = okToRetry
    end
  end
]]></fullcode>
class<nbsp/>RetryException<nbsp/>&lt;<nbsp/>RuntimeError
<nbsp/><nbsp/>attr<nbsp/>:okToRetry
<nbsp/><nbsp/>def<nbsp/>initialize(okToRetry)
<nbsp/><nbsp/><nbsp/><nbsp/>@okToRetry<nbsp/>=<nbsp/>okToRetry
<nbsp/><nbsp/>end
end
</alltt>
</codefragment>
<p/>
Somewhere down in the depths of the code, a transient error occurs.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  class RetryException < RuntimeError
!-    attr :okToRetry
!-    def initialize(okToRetry)
!-      @okToRetry = okToRetry
!-    end
!-  end
!-socket = STDIN
  def readData(socket)
    data = socket.read(512)
    if data.nil?
      raise RetryException.new(true), "transient read error"
    end
    # .. normal processing
  end
]]></fullcode>
def<nbsp/>readData(socket)
<nbsp/><nbsp/>data<nbsp/>=<nbsp/>socket.read(512)
<nbsp/><nbsp/>if<nbsp/>data.nil?
<nbsp/><nbsp/><nbsp/><nbsp/>raise<nbsp/>RetryException.new(true),<nbsp/>"transient<nbsp/>read<nbsp/>error"
<nbsp/><nbsp/>end
<nbsp/><nbsp/>#<nbsp/>..<nbsp/>normal<nbsp/>processing
end
</alltt>
</codefragment>
<p/>
Higher up the call stack, we handle the exception.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-  class RetryException < RuntimeError
!-    attr :okToRetry
!-    def initialize(okToRetry)
!-      @okToRetry = okToRetry
!-    end
!-  end
!-  def readData(socket)
!-    data = socket.read(512)
!-    if data.nil?
!-      raise RetryException.new(true), "transient read error"
!-    end
!-    # .. normal processing
!-  end
!-    socket = STDIN
  begin
    stuff = readData(socket)
    # .. process stuff
  rescue RetryException => detail
    retry if detail.okToRetry
    raise
  end
]]></fullcode>
begin
<nbsp/><nbsp/>stuff<nbsp/>=<nbsp/>readData(socket)
<nbsp/><nbsp/>#<nbsp/>..<nbsp/>process<nbsp/>stuff
rescue<nbsp/>RetryException<nbsp/>=&gt;<nbsp/>detail
<nbsp/><nbsp/>retry<nbsp/>if<nbsp/>detail.okToRetry
<nbsp/><nbsp/>raise
end
</alltt>
</codefragment>
<section>Catch and Throw</section>
<p/>
While the exception mechanism of <kw>raise</kw> and <kw>rescue</kw> is great
for abandoning execution when things go wrong, it's sometimes nice to
be able to jump out of some deeply nested construct during normal
processing. This is where <kw>catch</kw> and <kw>throw</kw> come in handy.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-songList = ""
!-def songList.play() end
catch (:done)  do
  while gets
    throw :done unless fields = split(/\t/)
    songList.add(Song.new(*fields))
  end
  songList.play
end
]]></fullcode>
catch<nbsp/>(:done)<nbsp/><nbsp/>do
<nbsp/><nbsp/>while<nbsp/>gets
<nbsp/><nbsp/><nbsp/><nbsp/>throw<nbsp/>:done<nbsp/>unless<nbsp/>fields<nbsp/>=<nbsp/>split(/\t/)
<nbsp/><nbsp/><nbsp/><nbsp/>songList.add(Song.new(*fields))
<nbsp/><nbsp/>end
<nbsp/><nbsp/>songList.play
end
</alltt>
</codefragment>
<p/>
<kw>catch</kw> defines a block that is labeled with the given name
(which may be a <classname>Symbol</classname> or a <classname>String</classname>). The block is executed
normally until a <kw>throw</kw> is encountered.
<p/>
When Ruby encounters a <kw>throw</kw>, it zips back up the call stack
looking for a <kw>catch</kw> block with a matching symbol.
When it finds
it, Ruby unwinds the stack to that point and terminates the block. If
the <kw>throw</kw> is called with the optional second parameter, that
value is returned as the value of the <kw>catch</kw>. So, in the previous
example, if the input does not contain correctly formatted lines, the
<kw>throw</kw> will skip to the end of the corresponding <kw>catch</kw>, not
only terminating the <tt>while</tt> loop but also skipping the playing of 
the song list.
<p/>
The following example uses a <kw>throw</kw> to terminate interaction with
the user if ``!'' is typed in response to any prompt.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[def promptAndGet(prompt)
  print prompt
  res = readline.chomp
  throw :quitRequested if res == "!"
  return res
end

catch :quitRequested do
  name = promptAndGet("Name: ")
  age  = promptAndGet("Age:  ")
  sex  = promptAndGet("Sex:  ")
  # ..
  # process information
end
]]></fullcode>
def<nbsp/>promptAndGet(prompt)
<nbsp/><nbsp/>print<nbsp/>prompt
<nbsp/><nbsp/>res<nbsp/>=<nbsp/>readline.chomp
<nbsp/><nbsp/>throw<nbsp/>:quitRequested<nbsp/>if<nbsp/>res<nbsp/>==<nbsp/>"!"
<nbsp/><nbsp/>return<nbsp/>res
end
<p/>
catch<nbsp/>:quitRequested<nbsp/>do
<nbsp/><nbsp/>name<nbsp/>=<nbsp/>promptAndGet("Name:<nbsp/>")
<nbsp/><nbsp/>age<nbsp/><nbsp/>=<nbsp/>promptAndGet("Age:<nbsp/><nbsp/>")
<nbsp/><nbsp/>sex<nbsp/><nbsp/>=<nbsp/>promptAndGet("Sex:<nbsp/><nbsp/>")
<nbsp/><nbsp/>#<nbsp/>..
<nbsp/><nbsp/>#<nbsp/>process<nbsp/>information
end
</alltt>
</codefragment>
<p/>
As this example illustrates, the <kw>throw</kw> does not have to appear within the
static scope of the <kw>catch</kw>.
</chapter>
</ppdoc>
