"SfR Fresh" - the SfR Freeware/Shareware Archive

Member "docs/script_guide/exceptions.html" of archive TestMaker.zip:


<HTML>
<!--This file created 10/18/02 4:07 PM by Claris Home Page version 3.0 30 Day Trial-->
<HEAD>
   <TITLE>TestMaker Script Guide - Errors and Exceptions</TITLE>
   <META NAME=GENERATOR CONTENT="Claris Home Page 3.0 30 Day Trial">
   <X-CLARIS-WINDOW TOP=114 BOTTOM=768 LEFT=16 RIGHT=546>
   <X-CLARIS-TAGVIEW MODE=minimal>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<H1><FONT FACE="Arial"><TABLE BORDER=0 BGCOLOR="#0000CC" CELLSPACING=1 CELLPADDING=0 WIDTH="100%">
   <TR>
      <TD>
         <P><FONT FACE="Arial"><TABLE BORDER=0 BGCOLOR="#FFFFCC" CELLSPACING=0 CELLPADDING=0 WIDTH="100%">
            <TR>
               <TD WIDTH=10>
                  <P><FONT FACE="Arial"><IMG SRC="../images/blank.gif" WIDTH=10 HEIGHT=1 X-CLARIS-USEIMAGEHEIGHT ALIGN=bottom></FONT></P>
               </TD>
               <TD WIDTH=120>
                  <P><A HREF="http://www.pushtotest.com"><FONT FACE="Arial"><IMG SRC="../images/ptt_logo_120w.gif" WIDTH=120 HEIGHT=32 X-CLARIS-USEIMAGEWIDTH X-CLARIS-USEIMAGEHEIGHT BORDER=0 ALIGN=bottom></FONT></A></P>
               </TD>
               <TD WIDTH=30>
                  <P><FONT FACE="Arial"><IMG SRC="../images/blank.gif" WIDTH=30 HEIGHT=1 X-CLARIS-USEIMAGEHEIGHT ALIGN=bottom></FONT></P>
               </TD>
               <TD>
                  <P><FONT FACE="Arial">TestMaker Script
                  Guide</FONT></P>
               </TD>
               <TD VALIGN=top ROWSPAN=3>
                  <P><A HREF="../index.html"><FONT SIZE="-1" FACE="Arial">Table
                  of Contents</FONT></A><FONT SIZE="-1" FACE="Arial"><BR>
                  <BR>
                  TestMaker Script Guide Chapters<BR>
                  </FONT><A HREF="script_index.html"><FONT SIZE="-1" FACE="Arial">Introduction</FONT></A><FONT SIZE="-1" FACE="Arial"><BR>
                  </FONT><A HREF="flow_control.html"><FONT SIZE="-1" FACE="Arial">Flow
                  Control</FONT></A><FONT SIZE="-1" FACE="Arial"><BR>
                  </FONT><A HREF="data_structures.html"><FONT SIZE="-1" FACE="Arial">Data
                  Structures</FONT></A><FONT SIZE="-1" FACE="Arial"><BR>
                  </FONT><A HREF="modules.html"><FONT SIZE="-1" FACE="Arial">Modules</FONT></A><FONT SIZE="-1" FACE="Arial"><BR>
                  </FONT><A HREF="input_output.html"><FONT SIZE="-1" FACE="Arial">Input
                  and Output</FONT></A><FONT SIZE="-1" FACE="Arial"><BR>
                  </FONT><A HREF="exceptions.html"><FONT SIZE="-1" FACE="Arial">Errors
                  and Exceptions</FONT></A><FONT SIZE="-1" FACE="Arial"><BR>
                  </FONT><A HREF="classes.html"><FONT SIZE="-1" FACE="Arial">Classes</FONT></A><FONT SIZE="-1" FACE="Arial"><BR>
                  </FONT><A HREF="floating_point.html"><FONT SIZE="-1" FACE="Arial">Floating
                  Point Numbers</FONT></A></P>
                  
                  <P></P>
               </TD>
            </TR>
            <TR>
               <TD WIDTH=10>
                  <P><FONT FACE="Arial"><IMG SRC="../images/blank.gif" WIDTH=10 HEIGHT=1 X-CLARIS-USEIMAGEHEIGHT ALIGN=bottom></FONT></P>
               </TD>
               <TD WIDTH=120>
                  <P><FONT FACE="Arial"><IMG SRC="../images/blank.gif" WIDTH=120 HEIGHT=1 X-CLARIS-USEIMAGEHEIGHT ALIGN=bottom></FONT></P>
               </TD>
               <TD WIDTH=30>
                  <P><FONT FACE="Arial"><IMG SRC="../images/blank.gif" WIDTH=30 HEIGHT=1 X-CLARIS-USEIMAGEHEIGHT ALIGN=bottom></FONT></P>
               </TD>
               <TD VALIGN=top>
                  <P><FONT SIZE="-1" FACE="Arial">Published: October
                  21, 2002<BR>
                  Applies to: TestMaker 3.0</FONT></P>
               </TD>
            </TR>
            <TR>
               <TD WIDTH=10>
                  <P><FONT FACE="Arial"><IMG SRC="../images/blank.gif" WIDTH=10 HEIGHT=1 X-CLARIS-USEIMAGEHEIGHT ALIGN=bottom></FONT></P>
               </TD>
               <TD WIDTH=120>
                  <P><FONT FACE="Arial"><IMG SRC="../images/blank.gif" WIDTH=120 HEIGHT=1 X-CLARIS-USEIMAGEHEIGHT ALIGN=bottom></FONT></P>
               </TD>
               <TD WIDTH=30>
                  <P><FONT FACE="Arial"><IMG SRC="../images/blank.gif" WIDTH=30 HEIGHT=1 X-CLARIS-USEIMAGEHEIGHT ALIGN=bottom></FONT></P>
               </TD>
               <TD VALIGN=top>
                  <P><FONT FACE="Arial"><IMG SRC="../images/blank.gif" WIDTH=30 HEIGHT=1 X-CLARIS-USEIMAGEHEIGHT ALIGN=bottom></FONT></P>
               </TD>
            </TR>
         </TABLE>
          </FONT></P>
      </TD>
   </TR>
</TABLE>
<BR>
Errors and Exceptions</FONT></H1>

<P><FONT FACE="Arial">Until now error messages haven't been more than
mentioned, but if you have tried out the examples you have probably
seen some. There are (at least) two distinguishable kinds of errors:
<I>syntax errors</I> and <I>exceptions</I>.</FONT></P>

<P>&nbsp;</P>

<H3><FONT COLOR="#000099">

<HR>

</FONT><FONT FACE="Arial" COLOR="#000099">Syntax Errors</FONT></H3>

<P><FONT FACE="Arial">Syntax errors, also known as parsing errors,
are perhaps the most common kind of complaint you get while you are
still learning Python:</FONT></P>

<P><FONT FACE="Arial">&nbsp;</FONT></P>

<BLOCKQUOTE class=verbatim><PRE class=verbatim>&gt;&gt;&gt; while 1 print 'Hello world'
  File "&lt;stdin&gt;", line 1, in ?
    while 1 print 'Hello world'
                ^
SyntaxError: invalid syntax
   </PRE></BLOCKQUOTE>

<P><FONT FACE="Arial">The parser repeats the offending line and
displays a little `arrow' pointing at the earliest point in the line
where the error was detected. The error is caused by (or at least
detected at) the token <I>preceding</I> the arrow: in the example,
the error is detected at the keyword <TT>print</TT>, since a colon
("<TT>:</TT>") is missing before it. File name and line number are
printed so you know where to look in case the input came from a
script.</FONT></P>

<H3><FONT FACE="Arial">

<HR>

</FONT><FONT FACE="Arial" COLOR="#000099">Exceptions</FONT></H3>

<P><FONT FACE="Arial">Even if a statement or expression is
syntactically correct, it may cause an error when an attempt is made
to execute it. Errors detected during execution are called
<I>exceptions</I> and are not unconditionally fatal: you will soon
learn how to handle them in Python programs. Most exceptions are not
handled by programs, however, and result in error messages as shown
here:</FONT></P>

<P><FONT FACE="Arial">&nbsp;</FONT></P>

<BLOCKQUOTE class=verbatim><PRE class=verbatim>&gt;&gt;&gt; 10 * (1/0)
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in ?
ZeroDivisionError: integer division or modulo
&gt;&gt;&gt; 4 + spam*3
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in ?
NameError: spam
&gt;&gt;&gt; '2' + 2
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in ?
TypeError: illegal argument type for built-in operation
   </PRE></BLOCKQUOTE>

<P><FONT FACE="Arial">The last line of the error message indicates
what happened. Exceptions come in different types, and the type is
printed as part of the message: the types in the example are
<TT>ZeroDivisionError</TT>, <TT>NameError</TT> and
<TT>TypeError</TT>. The string printed as the exception type is the
name of the built-in name for the exception that occurred. This is
true for all built-in exceptions, but need not be true for
user-defined exceptions (although it is a useful convention).
Standard exception names are built-in identifiers (not reserved
keywords).</FONT></P>

<P><FONT FACE="Arial">The rest of the line is a detail whose
interpretation depends on the exception type; its meaning is
dependent on the exception type.</FONT></P>

<P><FONT FACE="Arial">The preceding part of the error message shows
the context where the exception happened, in the form of a stack
backtrace. In general it contains a stack backtrace listing source
lines; however, it will not display lines read from standard
input.</FONT></P>

<P><FONT FACE="Arial">The </FONT><A HREF="../lib/module-exceptions.html" title="Python Library
Reference"><FONT FACE="Arial"><EM>Python Library
Reference</EM></FONT></A><FONT FACE="Arial"> lists the built-in
exceptions and their meanings.</FONT></P>

<P><FONT FACE="Arial">&nbsp;</FONT></P>

<H2><FONT FACE="Arial">

<HR>

</FONT><FONT FACE="Arial" COLOR="#000099">Handling
Exceptions</FONT></H2>

<P><FONT FACE="Arial">It is possible to write programs that handle
selected exceptions. Look at the following example, which asks the
user for input until a valid integer has been entered, but allows the
user to interrupt the program (using <KBD>Control-C</KBD> or whatever
the operating system supports); note that a user-generated
interruption is signalled by raising the <TT>KeyboardInterrupt</TT>
exception.</FONT></P>

<P><FONT FACE="Arial">&nbsp;</FONT></P>

<BLOCKQUOTE class=verbatim><PRE class=verbatim>&gt;&gt;&gt; while 1:
...     try:
...         x = int(raw_input("Please enter a number: "))
...         break
...     except ValueError:
...         print "Oops! That was no valid number.  Try again..."
...
   </PRE></BLOCKQUOTE>

<P><FONT FACE="Arial">The <TT>try</TT> statement works as
follows.</FONT></P>

<P><FONT FACE="Arial">&nbsp;</FONT></P>

<UL>
   <LI><FONT FACE="Arial">First, the <I>try clause</I> (the
   statement(s) between the <TT>try</TT> and <TT>except</TT>
   keywords) is executed.</FONT>
   
   <P><FONT FACE="Arial">&nbsp;</FONT></P></LI>
   
   <LI><FONT FACE="Arial">If no exception occurs, the <I>except
   clause</I> is skipped and execution of the <TT>try</TT> statement
   is finished.</FONT>
   
   <P><FONT FACE="Arial">&nbsp;</FONT></P></LI>
   
   <LI><FONT FACE="Arial">If an exception occurs during execution of
   the try clause, the rest of the clause is skipped. Then if its
   type matches the exception named after the <TT>except</TT>
   keyword, the rest of the try clause is skipped, the except clause
   is executed, and then execution continues after the <TT>try</TT>
   statement.</FONT>
   
   <P><FONT FACE="Arial">&nbsp;</FONT></P></LI>
   
   <LI><FONT FACE="Arial">If an exception occurs which does not match
   the exception named in the except clause, it is passed on to outer
   <TT>try</TT> statements; if no handler is found, it is an
   <I>unhandled exception</I> and execution stops with a message as
   shown above.</FONT>
   
   <P><FONT FACE="Arial">&nbsp;</FONT></P></LI>
</UL>

<P><FONT FACE="Arial">A <TT>try</TT> statement may have more than one
except clause, to specify handlers for different exceptions. At most
one handler will be executed. Handlers only handle exceptions that
occur in the corresponding try clause, not in other handlers of the
same <TT>try</TT> statement. An except clause may name multiple
exceptions as a parenthesized list, for example:</FONT></P>

<P>&nbsp;</P>

<BLOCKQUOTE class=verbatim><PRE class=verbatim>... except (RuntimeError, TypeError, NameError):
...     pass
   </PRE></BLOCKQUOTE>

<P><FONT FACE="Arial">The last except clause may omit the exception
name(s), to serve as a wildcard. Use this with extreme caution, since
it is easy to mask a real programming error in this way! It can also
be used to print an error message and then re-raise the exception
(allowing a caller to handle the exception as well):</FONT></P>

<P><FONT FACE="Arial">&nbsp;</FONT></P>

<BLOCKQUOTE class=verbatim><PRE class=verbatim>import string, sys
   
try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(string.strip(s))
except IOError, (errno, strerror):
    print "I/O error(%s): %s" % (errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()&#91;0&#93;
    raise
   </PRE></BLOCKQUOTE>

<P><FONT FACE="Arial">The <TT>try</TT> ... <TT>except</TT> statement
has an optional <I>else clause</I>, which, when present, must follow
all except clauses. It is useful for code that must be executed if
the try clause does not raise an exception. For example:</FONT></P>

<P>&nbsp;</P>

<BLOCKQUOTE class=verbatim><PRE class=verbatim>for arg in sys.argv&#91;1:&#93;:
    try:
        f = open(arg, 'r')
    except IOError:
        print 'cannot open', arg
    else:
        print arg, 'has', len(f.readlines()), 'lines'
        f.close()
   </PRE></BLOCKQUOTE>

<P><FONT FACE="Arial">The use of the <TT>else</TT> clause is better
than adding additional code to the <TT>try</TT> clause because it
avoids accidentally catching an exception that wasn't raised by the
code being protected by the <TT>try</TT> ... <TT>except</TT>
statement.</FONT></P>

<P><FONT FACE="Arial">When an exception occurs, it may have an
associated value, also known as the exception's <I>argument</I>. The
presence and type of the argument depend on the exception type. For
exception types which have an argument, the except clause may specify
a variable after the exception name (or list) to receive the
argument's value, as follows:</FONT></P>

<P>&nbsp;</P>

<BLOCKQUOTE class=verbatim><PRE class=verbatim>&gt;&gt;&gt; try:
...     spam()
... except NameError, x:
...     print 'name', x, 'undefined'
... 
name spam undefined
   </PRE></BLOCKQUOTE>

<P><FONT FACE="Arial">If an exception has an argument, it is printed
as the last part (`detail') of the message for unhandled
exceptions.</FONT></P>

<P><FONT FACE="Arial">Exception handlers don't just handle exceptions
if they occur immediately in the try clause, but also if they occur
inside functions that are called (even indirectly) in the try clause.
For example:</FONT></P>

<P><FONT FACE="Arial">&nbsp;</FONT></P>

<BLOCKQUOTE class=verbatim><PRE class=verbatim>&gt;&gt;&gt; def this_fails():
...     x = 1/0
... 
&gt;&gt;&gt; try:
...     this_fails()
... except ZeroDivisionError, detail:
...     print 'Handling run-time error:', detail
... 
Handling run-time error: integer division or modulo
   </PRE></BLOCKQUOTE>

<P>&nbsp;</P>

<H2><FONT FACE="Arial">

<HR>

Raising Exceptions</FONT></H2>

<P><FONT FACE="Arial">The <TT>raise</TT> statement allows the
programmer to force a specified exception to occur. For
example:</FONT></P>

<P><FONT FACE="Arial">&nbsp;</FONT></P>

<BLOCKQUOTE class=verbatim><PRE class=verbatim>&gt;&gt;&gt; raise NameError, 'HiThere'
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in ?
NameError: HiThere
   </PRE></BLOCKQUOTE>

<P><FONT FACE="Arial">The first argument to <TT>raise</TT> names the
exception to be raised. The optional second argument specifies the
exception's argument.</FONT></P>

<P><FONT FACE="Arial">If you need to determine whether an exception
was raised but don't intend to handle it, a simpler form of the
<TT>raise</TT> statement allows you to re-raise the
exception:</FONT></P>

<P>&nbsp;</P>

<BLOCKQUOTE class=verbatim><PRE class=verbatim>&gt;&gt;&gt; try:
...     raise NameError, 'HiThere'
... except NameError:
...     print 'An exception flew by!'
...     raise
...
An exception flew by!
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 2, in ?
NameError: HiThere
   </PRE></BLOCKQUOTE>

<P>&nbsp;</P>

<H2><FONT FACE="Arial" COLOR="#000099">

<HR>

User-defined Exceptions</FONT></H2>

<P><FONT FACE="Arial">Programs may name their own exceptions by
creating a new exception class. Exceptions should typically be
derived from the <TT>Exception</TT> class, either directly or
indirectly. For example:</FONT></P>

<P>&nbsp;</P>

<BLOCKQUOTE class=verbatim><PRE class=verbatim>&gt;&gt;&gt; class MyError(Exception):
...     def __init__(self, value):
...         self.value = value
...     def __str__(self):
...         return `self.value`
... 
&gt;&gt;&gt; try:
...     raise MyError(2*2)
... except MyError, e:
...     print 'My exception occurred, value:', e.value
... 
My exception occurred, value: 4
&gt;&gt;&gt; raise MyError, 'oops!'
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in ?
__main__.MyError: 'oops!'
   </PRE></BLOCKQUOTE>

<P><FONT FACE="Arial">Exception classes can be defined which do
anything any other class can do, but are usually kept simple, often
only offering a number of attributes that allow information about the
error to be extracted by handlers for the exception. When creating a
module which can raise several distinct errors, a common practice is
to create a base class for exceptions defined by that module, and
subclass that to create specific exception classes for different
error conditions:</FONT></P>

<P>&nbsp;</P>

<BLOCKQUOTE class=verbatim><PRE class=verbatim>class Error(Exception):
    """Base class for exceptions in this module."""
    pass
   
class InputError(Error):
    """Exception raised for errors in the input.
   
    Attributes:
        expression -- input expression in which the error occurred
        message -- explanation of the error
    """
   
    def __init__(self, expression, message):
        self.expression = expression
        self.message = message
   
class TransitionError(Error):
    """Raised when an operation attempts a state transition that's not
    allowed.
   
    Attributes:
        previous -- state at beginning of transition
        next -- attempted new state
        message -- explanation of why the specific transition is not allowed
    """
   
    def __init__(self, previous, next, message):
        self.previous = previous
        self.next = next
        self.message = message
   </PRE></BLOCKQUOTE>

<P><FONT FACE="Arial">Most exceptions are defined with names that end
in ``Error,'' similar to the naming of the standard
exceptions.</FONT></P>

<P><FONT FACE="Arial">Many standard modules define their own
exceptions to report errors that may occur in functions they define.
More information on classes is presented in chapter </FONT><A HREF="node11.html#classes"><FONT FACE="Arial">9</FONT></A><FONT FACE="Arial">,
``Classes.''</FONT></P>

<P><FONT FACE="Arial">&nbsp;</FONT></P>

<H2><FONT FACE="Arial">

<HR>

</FONT><FONT FACE="Arial" COLOR="#000099">Defining Clean-up
Actions</FONT></H2>

<P><FONT FACE="Arial">The <TT>try</TT> statement has another optional
clause which is intended to define clean-up actions that must be
executed under all circumstances. For example:</FONT></P>

<P>&nbsp;</P>

<BLOCKQUOTE class=verbatim><PRE class=verbatim>&gt;&gt;&gt; try:
...     raise KeyboardInterrupt
... finally:
...     print 'Goodbye, world!'
... 
Goodbye, world!
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 2, in ?
KeyboardInterrupt
   </PRE></BLOCKQUOTE>

<P><FONT FACE="Arial">A <I>finally clause</I> is executed whether or
not an exception has occurred in the try clause. When an exception
has occurred, it is re-raised after the finally clause is executed.
The finally clause is also executed ``on the way out'' when the
<TT>try</TT> statement is left via a <TT>break</TT> or
<TT>return</TT> statement.</FONT></P>

<P><FONT FACE="Arial">The code in the finally clause is useful for
releasing external resources (such as files or network connections),
regardless of whether or not the use of the resource was
successful.</FONT></P>

<P><FONT FACE="Arial">A <TT>try</TT> statement must either have one
or more except clauses or one finally clause, but not
both.</FONT></P>

<H2><FONT FACE="Arial" COLOR="#0033FF">&nbsp;</FONT><FONT FACE="Arial" COLOR="#000099">

<HR>

What's Next?</FONT></H2>

<P><FONT FACE="Arial">Choose one of the other chapters in the
Scripting Guide:</FONT></P>

<OL>
   <LI><A HREF="#Data"><FONT FACE="Arial">DataTypes</FONT></A></LI>
   
   <LI><A HREF="flow_control.html"><FONT FACE="Arial">Flow Control
   and Functions</FONT></A></LI>
   
   <LI><A HREF="data_structures.html"><FONT FACE="Arial">Data
   Structures</FONT></A></LI>
   
   <LI><A HREF="modules.html"><FONT FACE="Arial">Modules</FONT></A></LI>
   
   <LI><A HREF="input_output.html"><FONT FACE="Arial">Input and
   Output</FONT></A></LI>
   
   <LI><A HREF="exceptions.html"><FONT FACE="Arial">Errors and
   Exceptions</FONT></A></LI>
   
   <LI><A HREF="classes.html"><FONT FACE="Arial">Classes</FONT></A></LI>
   
   <LI><A HREF="floating_point.html"><FONT FACE="Arial">Floating
   Point Numbers</FONT></A></LI>
</OL>

<PRE>

<FONT FACE="Arial"> </FONT></PRE>

<P><FONT FACE="Arial"><TABLE BORDER=0 BGCOLOR="#0000CC" CELLSPACING=1 CELLPADDING=0 WIDTH="100%">
   <TR>
      <TD>
         <P><FONT FACE="Arial"><TABLE BORDER=0 BGCOLOR="#FFFFCC" CELLPADDING=0 WIDTH="100%">
            <TR>
               <TD WIDTH=10>
                  <P><FONT FACE="Arial"><IMG SRC="../images/blank.gif" WIDTH=10 HEIGHT=1 X-CLARIS-USEIMAGEHEIGHT ALIGN=bottom></FONT></P>
               </TD>
               <TD WIDTH=120>
                  <P><A HREF="http://www.pushtotest.com"><FONT FACE="Arial"><IMG SRC="../images/ptt_logo_120w.gif" WIDTH=120 HEIGHT=32 X-CLARIS-USEIMAGEWIDTH X-CLARIS-USEIMAGEHEIGHT BORDER=0 ALIGN=bottom></FONT></A></P>
               </TD>
               <TD WIDTH=30>
                  <P><FONT FACE="Arial"><IMG SRC="../images/blank.gif" WIDTH=30 HEIGHT=1 X-CLARIS-USEIMAGEHEIGHT ALIGN=bottom></FONT></P>
               </TD>
               <TD>
                  <P><FONT SIZE="-1" FACE="Arial">Additional
                  documentation, product downloads and updates are at
                  </FONT><A HREF="http://www.pushtotest.com"><FONT SIZE="-1" FACE="Arial">www.PushToTest.com</FONT></A><FONT SIZE="-1" FACE="Arial">.
                  While the TestMaker software is distributed under
                  an open-source license, the documentation remains
                  (c) 2002 PushToTest. All rights
                  reserved.</FONT></P>
               </TD>
            </TR>
         </TABLE>
          </FONT></P>
      </TD>
   </TR>
</TABLE>
 </FONT></P>
</BODY>
</HTML>