Text stringlengths 1 9.41k |
|---|
The message consists of a stack trace
(“Traceback”) and the name of and details about the exception that was raised. |
The
stack trace lists all lines active when the exception occurred, from oldest to newest.
Note that because we’re not working at the interactive prompt, in this case the file and
line number information is more useful. |
For example, here we can see that the bad
divide happens at the last entry in the trace—line 2 of the file _bad.py, a_ `return`
statement.[*]
Because Python detects and reports all errors at runtime by raising exceptions, exceptions are intimately bound up with the ideas of error handling and debugging in general.
- ... |
Don’t be alarmed if your error messages don’t exactly match mine. |
When I ran this example in
Python 3.0’s IDLE GUI, for instance, its error message text showed filenames with full absolute directory
paths.
**|**
-----
If you’ve worked through this book’s examples, you’ve undoubtedly seen an exception
or two along the way—even typos usually generate a SyntaxError or other exceptio... |
By default, you
get a useful error display like the one just shown, which helps you track down the
problem.
Often, this standard error message is all you need to resolve problems in your code.
For more heavy-duty debugging jobs, you can catch exceptions with try statements,
or use one of the debugging tools that I int... |
For many programs, there is no need to be more specific about errors in your
code.
Sometimes, though, you’ll want to catch errors and recover from them instead. |
If you
don’t want your program terminated when Python raises an exception, simply catch it
by wrapping the program logic in a try. |
This is an important capability for programs
such as network servers, which must keep running persistently. |
For example, the following code catches and recovers from the TypeError Python raises immediately when
you try to concatenate a list and a string (the + operator expects the same sequence type
on both sides):
```
def kaboom(x, y):
print(x + y) # Trigger TypeError
try:
kaboom([0,1,2], "spam")
except... |
Since an exception is “dead” after it’s been
```
caught like this, the program continues executing below the try rather than being terminated by Python. |
In effect, the code processes and clears the error, and your script
recovers:
```
% python kaboom.py
Hello world!
resuming here
```
Notice that once you’ve caught an error, control resumes at the place where you caught
it (i.e., after the try); there is no direct way to go back to the place where the exception
o... |
In a sense, this makes exceptions more like
**|**
-----
simple jumps than function calls—there is no way to return to the code that triggered
the error.
###### The try/finally Statement
The other flavor of the try statement is a specialization that has to do with finalization
actions. |
If a finally clause is included in a try, Python will always run its block of
statements “on the way out” of the try statement, whether an exception occurred while
the try block was running or not. |
Its general form is:
```
try:
<statements> # Run this action first
finally:
<statements> # Always run this code on the way out
```
With this variant, Python begins by running the statement block associated with the
```
try header line. |
What happens next depends on whether an exception occurs during
```
the try block:
- If no exception occurs while the try block is running, Python jumps back to run
the finally block and then continues execution past below the try statement.
- If an exception does occur during the try block’s run, Python still com... |
That is, the finally block is run even if an exception is raised, but
```
unlike an except, the finally does not terminate the exception—it continues being
raised after the finally block runs.
The try/finally form is useful when you want to be completely sure that an action will
happen after some code runs, regardles... |
In
practice, it allows you to specify cleanup actions that always must occur, such as file
closes and server disconnects.
Note that the finally clause cannot be used in the same try statement as except and
```
else in Python 2.4 and earlier, so the try/finally is best thought of as a distinct state
```
ment form if yo... |
In Python 2.5, and later, however,
```
finally can appear in the same statement as except and else, so today there is really a
```
single try statement with many optional clauses (more about this shortly). |
Whichever
version you use, though, the finally clause still serves the same purpose—to specify
“cleanup” actions that must always be run, regardless of any exceptions.
As we’ll also see later in this chapter, in Python 2.6 and 3.0, the new
```
with statement and its context managers provide an object-based way
... |
Unlike finally, this new statement
also supports entry actions, but it is limited in scope to objects that
implement the context manager protocol.
**|**
-----
###### Example: Coding Termination Actions with try/finally
We saw some simple try/finally examples in the prior chapter. |
Here’s a more realistic
example that illustrates a typical role for this statement:
```
class MyError(Exception): pass
def stuff(file):
raise MyError()
file = open('data', 'w') # Open an output file
try:
stuff(file) # Raises exception
finally:
file.close() # Always close file to flus... |
This way, later code can be sure that the file’s
output buffer’s content has been flushed from memory to disk. |
A similar code structure
can guarantee that server connections are closed, and so on.
As we learned in Chapter 9, file objects are automatically closed on garbage collection;
this is especially useful for temporary files that we don’t assign to variables. |
However,
it’s not always easy to predict when garbage collection will occur, especially in larger
programs. |
The try statement makes file closes more explicit and predictable and pertains to a specific block of code. |
It ensures that the file will be closed on block exit,
regardless of whether an exception occurs or not.
This particular example’s function isn’t all that useful (it just raises an exception), but
wrapping calls in try/finally statements is a good way to ensure that your closing-time
(i.e., termination) activities alw... |
Again, Python always runs the code in your
```
finally blocks, regardless of whether an exception happens in the try block.[†]
```
When the function here raises its exception, the control flow jumps back and runs the
```
finally block to close the file. |
The exception is then propagated on to either another
try or the default top-level handler, which prints the standard error message and shuts
```
down the program; the statement after this try is never reached. |
If the function here
did not raise an exception, the program would still execute the finally block to close
the file, but it would then continue below the entire try statement.
Notice that the user-defined exception here is again defined with a class—as we’ll see
in the next chapter, exceptions today must all be class... |
It does a good job of avoiding this, though, by checking all
possible errors as a program runs. |
When a program does crash hard, it is usually due to a bug in linked-in C
extension code, outside of Python’s scope.
**f** **|**
-----
###### Unified try/except/finally
In all versions of Python prior to Release 2.5 (for its first 15 years of life, more or less),
the `try statement came in two flavors and was real... |
This was partly
because of implementation issues, and partly because the meaning of mixing the two
seemed obscure—catching and recovering from exceptions seemed a disjoint concept
from performing cleanup actions.
In Python 2.5 and later, though (including 2.6 and 3.0, the versions used in this book),
the two statement... |
Today, we can mix finally, except, and else clauses
in the same statement. |
That is, we can now write a statement of this form:
```
try: # Merged form
main-action
except Exception1:
handler1
except Exception2:
handler2
...
else:
else-block
finally:
finally-block
```
The code in this statement’s main-action block is executed first, as usual. |
If that code
raises an exception, all the except blocks are tested, one after another, looking for a
match to the exception raised. |
If the exception raised is Exception1, the handler1 block
is executed; if it’s Exception2, handler2 is run, and so on. |
If no exception is raised, the
```
else-block is executed.
```
No matter what’s happened previously, the finally-block is executed once the main
action block is complete and any raised exceptions have been handled. |
In fact, the code
in the finally-block will be run even if there is an error in an exception handler or the
```
else-block and a new exception is raised.
```
As always, the finally clause does not end the exception—if an exception is active
when the finally-block is executed, it continues to be propagated after the fi... |
If no exception is active when the finally is run, control
resumes after the entire try statement.
The net effect is that the finally is always run, regardless of whether:
- An exception occurred in the main action and was handled.
- An exception occurred in the main action and was not handled.
**|**
-----
- ... |
Really, the try statement consists
of two parts: excepts with an optional else, and/or the finally.
In fact, it’s more accurate to describe the merged statement’s syntactic form this way
(square brackets mean optional and star means zero-or-more here):
```
try: # Format 1
statements
except [type... |
It’s also possible to mix finally and else, but only if an except appears too (though
the except can omit an exception name to catch everything and run a raise statement,
described later, to reraise the current exception). |
If you violate any of these ordering
rules, Python will raise a syntax error exception before your code runs.
###### Combining finally and except by Nesting
Prior to Python 2.5, it is actually possible to combine finally and except clauses in a
```
try by syntactically nesting a try/except in the try block of a try/f... |
In fact, the following has the
same effect as the new merged form shown at the start of this section:
**f** **f** **|**
-----
```
try: # Nested equivalent to merged form
try:
main-action
except Exception1:
handler1
except Exception2:
handler2
...
else:
no... |
Since an
```
else always requires an except, this nested form even sports the same mixing con
```
straints of the unified statement form outlined in the preceding section.
However, this nested equivalent is more obscure and requires more code than the new
merged form (one four-character line, at least). |
Mixing finally into the same statement
makes your code easier to write and read, so this is the generally preferred technique
today.
###### Unified try Example
Here’s a demonstration of the merged try statement form at work. |
The following file,
_mergedexc.py, codes four common scenarios, with print statements that describe the_
meaning of each:
```
sep = '-' * 32 + '\n'
print(sep + 'EXCEPTION RAISED AND CAUGHT')
try:
x = 'spam'[99]
except IndexError:
print('except run')
finally:
print('finally run')
print('after run... |
Trace through the code to see how exception handling produces the output of
each of the four tests here:
```
c:\misc> C:\Python30\python mergedexc.py
------------------------------- EXCEPTION RAISED AND CAUGHT
except run
finally run
after run
------------------------------- NO EXCEPTION RAISED
finally r... |
The
next section shows how to raise exceptions manually instead.
**f** **f** **|**
-----
###### The raise Statement
To trigger exceptions explicitly, you can code raise statements. |
Their general form is
simple—a raise statement consists of the word raise, optionally followed by the class
to be raised or an instance of it:
```
raise <instance> # Raise instance of class
raise <class> # Make and raise instance of class
raise # Reraise the most recent exception
```
As m... |
If we pass a class
instead, Python calls the class with no constructor arguments, to create an instance to
be raised; this form is equivalent to adding parentheses after the class reference. |
The
last form reraises the most recently raised exception; it’s commonly used in exception
handlers to propagate exceptions that have been caught.
To make this clearer, let’s look at some examples. |
With built-in exceptions, the following two forms are equivalent—both raise an instance of the exception class named,
but the first creates the instance implicitly:
```
raise IndexError # Class (instance created)
raise IndexError() # Instance (created in statement)
```
We can also create the instance ah... |
Once caught by an except clause anywhere
in the program, an exception dies (i.e., won’t propagate to another `try), unless it’s`
reraised by another raise statement or error.
###### Propagating Exceptions with raise
A raise statement that does not include an exception name or extra data value simply
reraises the curr... |
This form is typically used if you need to catch and
handle an exception but don’t want the exception to die in your code:
```
>>> try:
```
`... |
raise IndexError('spam')` _# Exceptions remember arguments_
```
... except IndexError:
... print('propagating')
```
`... |
raise` _# Reraise most recent exception_
```
...
propagating
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
IndexError: spam
```
Running a raise this way reraises the exception and propagates it to a higher handler
(or the default handler at the top, which stops the program with a st... |
Notice how the argument we passed to the exception class shows up in the error
messages; you’ll learn why this happens in the next chapter.
###### Python 3.0 Exception Chaining: raise from
Python 3.0 (but not 2.6) also allows raise statements to have an optional from clause:
```
raise exception from otherexception
... |
If the raised exception is
not caught, Python prints both exceptions as part of the standard error message:
```
>>> try:
... 1 / 0
... except Exception as E:
```
**|**
-----
```
... |
raise TypeError('Bad!') from E
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ZeroDivisionError: int division or modulo by zero
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
TypeEr... |
This is an advanced and still somewhat obscure extension, so
see Python’s manuals for more details.
_Version skew note: Python 3.0 no longer supports the raise_ `Exc,` `Args`
form that is still available in Python 2.6. |
In 3.0, use the `raise`
```
Exc(Args) instance-creation call form described in this book instead.
```
The equivalent comma form in 2.6 is legacy syntax provided for compatibility with the now defunct string-based exceptions model, and it’s
deprecated in 3.0. |
If used, it is converted to the 3.0 call form. |
As in earlier
releases, a `raise` `Exc form is also allowed—it is converted to` `raise`
```
Exc() in both versions, calling the class constructor with no arguments.
###### The assert Statement
```
As a somewhat special case for debugging purposes, Python includes the assert statement. |
It is mostly just syntactic shorthand for a common raise usage pattern, and an
```
assert can be thought of as a conditional raise statement. |
A statement of the form:
assert <test>, <data> # The <data> part is optional
```
works like the following code:
```
if __debug__:
if not <test>:
raise AssertionError(<data>)
```
In other words, if the test evaluates to false, Python raises an exception: the data item
(if it’s provided) is used as th... |
Like all exceptions,
the AssertionError exception will kill your program if it’s not caught with a try, in
which case the data item shows up as part of the error message.
As an added feature, assert statements may be removed from a compiled program’s
byte code if the -O Python command-line flag is used, thereby optimi... |
Use a command line like python –O
```
main.py to run in optimized mode and disable asserts.
###### Example: Trapping Constraints (but Not Errors!)
```
Assertions are typically used to verify program conditions during development. |
When
displayed, their error message text automatically includes source code line information
and the value listed in the assert statement. |
Consider the file asserter.py:
```
def f(x):
assert x < 0, 'x must be negative'
return x ** 2
% python
>>> import asserter
>>> asserter.f(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "asserter.py", line 2, in f
assert x < 0, 'x must be negative'
AssertionE... |
Because Python traps programming errors itself, there is usually no need to code asserts to catch things like outof-bounds indexes, type mismatches, and zero divides:
```
def reciprocal(x):
assert x != 0 # A useless assert!
return 1 / x # Python checks for zero automatically
```
Such asserts are... |
This statement is designed to work with context manager objects,
which support a new method-based protocol. |
This feature is also available as an option
in 2.5, enabled with an import of this form:
```
from __future__ import with_statement
```
‡ In most cases, at least. |
As suggested earlier in the book, if a function has to perform long-running or
unrecoverable actions before it reaches the place where an exception will be triggered, you still might want
to test for errors. |
Even in this case, though, be careful not to make your tests overly specific or restrictive, or
you will limit your code’s utility.
**|**
-----
In short, the `with/as statement is designed to be an alternative to a common` `try/`
```
finally usage idiom; like that statement, it is intended for specifying terminatio... |
Unlike `try/finally, though, the` `with statement supports a richer`
object-based protocol for specifying both entry and exit actions around a block of code.
Python enhances some built-in tools with context managers, such as files that automatically close themselves and thread locks that automatically lock and unlock,... |
This object may also return a value
that will be assigned to the name variable if the optional as clause is present.
Note that the variable is not necessarily assigned the result of the expression; the result
of the expression is the object that supports the context protocol, and the variable may
be assigned something... |
The object returned by the expression may then run startup code before the with-block is started,
as well as termination code after the block is done, regardless of whether the block
raised an exception or not.
Some built-in Python objects have been augmented to support the context management
protocol, and so can be u... |
For example, file objects (covered
in Chapter 9) have a context manager that automatically closes the file after the with
block regardless of whether an exception is raised:
```
with open(r'C:\misc\data') as myfile:
for line in myfile:
print(line)
...more code here...
```
Here, the call to open retur... |
After this with statement has run, the context management machinery
```
guarantees that the file object referenced by myfile is automatically closed, even if the
```
for loop raised an exception while processing the file.
```
Although file objects are automatically closed on garbage collection, it’s not always
straig... |
The with statement in this role is an
alternative that allows us to be sure that the close will occur after execution of a specific
**|**
-----
block of code. |
As we saw earlier, we can achieve a similar effect with the more general
and explicit `try/finally statement, but it requires four lines of administrative code`
instead of one in this case:
```
myfile = open(r'C:\misc\data')
try:
for line in myfile:
print(line)
...more code here...
finally:
my... |
To do the same with a `try/`
```
finally, we would need to save the context before and restore it manually.
###### The Context Management Protocol
```
Although some built-in types come with context managers, we can also write new ones
of our own. |
To implement context managers, classes use special methods that fall into
the operator overloading category to tap into the with statement. |
The interface expected
of objects used in with statements is somewhat complex, and most programmers only
need to know how to use existing context managers. |
For tool builders who might want
to write new application-specific context managers, though, let’s take a quick look at
what’s involved.
Here’s how the with statement actually works:
**|**
-----
1. |
The expression is evaluated, resulting in an object known as a context manager that
must have __enter__ and __exit__ methods.
2. The context manager’s __enter__ method is called. |
The value it returns is assigned
to the variable in the as clause if present, or simply discarded otherwise.
3. The code in the nested with block is executed.
4. |
If the with block raises an exception, the __exit__(type, `value,` `traceback) method`
is called with the exception details. |
Note that these are the same values returned
by sys.exc_info, described in the Python manuals and later in this part of the book.
If this method returns a false value, the exception is reraised; otherwise, the exception is terminated. |
The exception should normally be reraised so that it is
propagated outside the with statement.
5. |
If the with block does not raise an exception, the __exit__ method is still called,
but its type, value, and traceback arguments are all passed in as None.
Let’s look at a quick demo of the protocol in action. |
The following defines a context
manager object that traces the entry and exit of the with block in any with statement it
is used for:
```
class TraceBlock:
def message(self, arg):
print('running', arg)
def __enter__(self):
print('starting with block')
return self
def __exit__(self, exc_t... |
Also notice that the __enter__ method returns
```
self as the object to assign to the as variable; in other use cases, this might return a
```
completely different object instead.
When run, the context manager traces the entry and exit of the with statement block
with its __enter__ and __exit__ methods. |
Here’s the script in action being run under
Python 3.0 (it runs in 2.6, too, but prints some extra tuple parentheses):
**|**
-----
```
% python withas.py
starting with block
running test 1
reached
exited normally
starting with block
running test 2
raise an exception! |
<class 'TypeError'>
Traceback (most recent call last):
File "withas.py", line 20, in <module>
raise TypeError
TypeError
```
Context managers are somewhat advanced devices for tool builders, so we’ll skip additional details here (see Python’s standard manuals for the full story—for example,
there’s a new con... |
For simpler purposes, the try/finally statement provides sufficient
support for termination-time activities.
In the upcoming Python 3.1 release, the with statement may also specify
multiple (sometimes referred to as “nested”) context managers with new
comma syntax. |
In the following, for example, both files’ exit actions are
automatically run when the statement block exits, regardless of exception outcomes:
```
with open('data') as fin, open('res', 'w') as fout:
for line in fin:
if 'some key' in line:
fout.write(line)
```
Any nu... |
In general, the 3.1 (and later)
code:
```
with A() as a, B() as b:
...statements...
```
is equivalent to the following, which works in 3.1, 3.0, and 2.6:
```
with A() as a:
with B() as b:
...statements...
```
See Python 3.1 release notes for additional details... |
The next chapter continues our exploration by describing how to implement exception objects of
your own; as you’ll see, classes allow you to code new exceptions specific to your
programs. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.