Section 10.2. Exceptions in Python


10.2. Exceptions in Python

As you were going through some of the examples in the previous chapters, you no doubt noticed what happens when your program "crashes" or terminates due to unresolved errors. A "traceback" notice appears along with a notice containing as much diagnostic information as the interpreter can give you, including the error name, reason, and perhaps even the line number near or exactly where the error occurred. All errors have a similar format, regardless of whether running within the Python interpreter or standard script execution, providing a consistent error interface. All errors, whether they be syntactical or logical, result from behavior incompatible with the Python interpreter and cause exceptions to be raised.

Let us take a look at some exceptions now.

NameError: attempt to access an undeclared variable

>>> foo Traceback (innermost last):  File "<stdin>", line 1, in ? NameError: name 'foo' is not defined


NameError indicates access to an uninitialized variable. The offending identifier was not found in the Python interpreter's symbol table. We will be discussing namespaces in the next two chapters, but as an introduction, regard them as "address books" linking names to objects. Any object that is accessible should be listed in a namespace. Accessing a variable entails a search by the interpreter, and if the name requested is not found in any of the namespaces, a NameError exception will be generated.

ZeroDivisionError: division by any numeric zero

>>> 1/0 Traceback (innermost last):  File "<stdin>", line 1, in ? ZeroDivisionError: integer division or modulo by zero


Our example above used floats, but in general, any numeric division-by-zero will result in a ZeroDivisionError exception.

SyntaxError: Python interpreter syntax error

>>> for   File "<string>", line 1     for        ^ SyntaxError: invalid syntax


SyntaxError exceptions are the only ones that do not occur at run-time. They indicate an improperly constructed piece of Python code which cannot execute until corrected. These errors are generated at compile-time, when the interpreter loads and attempts to convert your script to Python bytecode. These may also occur as a result of importing a faulty module.

IndexError: request for an out-of-range index for sequence

>>> aList = [] >>> aList[0] Traceback (innermost last):   File "<stdin>", line 1, in ? IndexError: list index out of range


IndexError is raised when attempting to access an index that is outside the valid range of a sequence.

KeyError: request for a non-existent dictionary key

>>> aDict = {'host': 'earth', 'port': 80} >>> print aDict['server'] Traceback (innermost last):   File "<stdin>", line 1, in ? KeyError: server


Mapping types such as dictionaries depend on keys to access data values. Such values are not retrieved if an incorrect/nonexistent key is requested. In this case, a KeyErroris raised to indicate such an incident has occurred.

IOError: input/output error

>>> f = open("blah") Traceback (innermost last):   File "<stdin>", line 1, in ? IOError: [Errno 2] No such file or directory: 'blah'


Attempting to open a nonexistent disk file is one example of an operating system input/output (I/O) error. Any type of I/O error raises an IOError exception.

AttributeError: attempt to access an unknown object attribute

>>> class myClass(object): ...      pass ... >>> myInst = myClass() >>> myInst.bar = 'spam' >>> myInst.bar 'spam' >>> myInst.foo Traceback (innermost last):   File "<stdin>", line 1, in ? AttributeError: foo


In our example, we stored a value in myInst.bar, the bar attribute of instance myInst. Once an attribute has been defined, we can access it using the familiar dotted-attribute notation, but if it has not, as in our case with the foo (non-)attribute, an AttributeError occurs.



Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net