Text stringlengths 1 9.41k |
|---|
print(X)
```
**|**
-----
```
...
Always look on the bright side of life...
>>> raise MyBad()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
__main__.MyBad: Always look on the bright side of life...
```
A subtle point to note here is that you generally must redefine __str__ for ... |
If you define a __repr__, printing will happily call the superclass’s __str__ instead! |
See Chapter 29 for more details
on these special methods.
Whatever your method returns is included in error messages for uncaught exceptions
and used when exceptions are printed explicitly. |
The method returns a hardcoded
string here to illustrate, but it can also perform arbitrary text processing, possibly using
state information attached to the instance object. |
The next section looks at state information options.
###### Custom Data and Behavior
Besides supporting flexible hierarchies, exception classes also provide storage for extra
state information as instance attributes. |
As we saw earlier, built-in exception superclasses provide a default constructor that automatically saves constructor arguments
in an instance tuple attribute named args. |
Although the default constructor is adequate
for many cases, for more custom needs we can provide a constructor of our own. |
In
addition, classes may define methods for use in handlers that provide precoded exception processing logic.
###### Providing Exception Details
When an exception is raised, it may cross arbitrary file boundaries—the raise statement that triggers an exception and the try statement that catches it may be in completely... |
It is not generally feasible to store extra details in global
variables because the try statement might not know which file the globals reside in.
Passing extra state information along in the exception itself allows the try statement
to access it more reliably.
With classes, this is nearly automatic. |
As we’ve seen, when an exception is raised,
Python passes the class instance object along with the exception. |
Code in try statements
can access the raised instance by listing an extra variable after the as keyword in an
```
except handler. |
This provides a natural hook for supplying data and behavior to the
```
handler.
**|**
-----
For example, a program that parses data files might signal a formatting error by raising
an exception instance that is filled out with extra details about the error:
```
>>> class FormatError(Exception):
... |
def __init__(self, line, file):
... self.line = line
... self.file = file
...
>>> def parser():
```
`... raise FormatError(42, file='spam.txt')` _# When error found_
```
...
>>> try:
... |
parser()
... except FormatError as X:
... |
print('Error at', X.file, X.line)
...
Error at spam.txt 42
```
In the except clause here, the variable X is assigned a reference to the instance that was
generated when the exception was raised.[†] This gives access to the attributes attached
to the instance by the custom constructor. |
Although we could rely on the default state
retention of built-in superclasses, it’s less relevant to our application:
`>>> class FormatError(Exception): pass` _# Inherited constructor_
```
...
>>> def parser():
```
`... |
raise FormatError(42, 'spam.txt')` _# No keywords allowed!_
```
...
>>> try:
... parser()
... except FormatError as X:
```
`... |
print('Error at:', X.args[0], X.args[1])` _# Not specific to this app_
```
...
Error at: 42 spam.txt
###### Providing Exception Methods
```
Besides enabling application-specific state information, custom constructors also better
support extra behavior for exception objects. |
That is, the exception class can also define
_methods to be called in the handler. |
The following, for example, adds a method that_
uses exception state information to log errors to a file:
```
class FormatError(Exception):
logfile = 'formaterror.txt'
def __init__(self, line, file):
self.line = line
self.file = file
```
† As suggested earlier, the raised instance object is also ... |
More on sys.exc_info
in the next chapter.
**|**
-----
```
def logerror(self):
log = open(self.logfile, 'a')
print('Error at', self.file, self.line, file=log)
def parser():
raise FormatError(40, 'spam.txt')
try:
parser()
except FormatError as exc:
exc.logerror()
```
When run, this ... |
Moreover, exception classes are
free to customize and extend inherited behavior. |
In other words, because they are defined with classes, all the benefits of OOP that we studied in Part VI are available for
use with exceptions in Python.
###### Chapter Summary
In this chapter, we explored coding user-defined exceptions. |
As we learned, exceptions
are implemented as class instance objects in Python 2.6 and 3.0 (an earlier string-based
exception model alternative was available in earlier releases but has now been deprecated). |
Exception classes support the concept of exception hierarchies that ease maintenance, allow data and behavior to be attached to exceptions as instance attributes
and methods, and allow exceptions to inherit data and behavior from superclasses.
We saw that in a try statement, catching a superclass catches that class as... |
We also
saw that the built-in exception superclasses we must inherit from provide usable defaults for printing and state retention, which we can override if desired.
The next chapter wraps up this part of the book by exploring some common use cases
for exceptions and surveying tools commonly used by Python programmers... |
Before we
get there, though, here’s this chapter’s quiz.
**|**
-----
###### Test Your Knowledge: Quiz
1. What are the two new constraints on user-defined exceptions in Python 3.0?
2. |
How are raised class-based exceptions matched to handlers?
3. Name two ways that you can attach context information to exception objects.
4. |
Name two ways that you can specify the error message text for exception objects.
5. Why should you not use string-based exceptions anymore today?
###### Test Your Knowledge: Answers
1. |
In 3.0, exceptions must be defined by classes (that is, a class instance object is raised
and caught). |
In addition, exception classes must be derived from the built-in class
```
BaseException (most programs inherit from its Exception subclass, to support
```
catchall handlers for normal kinds of exceptions).
2. |
Class-based exceptions match by superclass relationships: naming a superclass in
an exception handler will catch instances of that class, as well as instances of any
of its subclasses lower in the class tree. |
Because of this, you can think of superclasses
as general exception categories and subclasses as more specific types of exceptions
within those categories.
3. |
You can attach context information to class-based exceptions by filling out instance
attributes in the instance object raised, usually in a custom class constructor. |
For
simpler needs, built-in exception superclasses provide a constructor that stores its
arguments on the instance automatically (in the attribute args). |
In exception handlers, you list a variable to be assigned to the raised instance, then go through this
name to access attached state information and call any methods defined in the class.
4. |
The error message text in class-based exceptions can be specified with a custom
```
__str__ operator overloading method. |
For simpler needs, built-in exception su
```
perclasses automatically display anything you pass to the class constructor. |
Operations like `print and` `str automatically fetch the display string of an exception`
object when is it printed either explicitly or as part of an error message.
5. |
Because Guido said so—they have been removed in both Python 2.6 and 3.0.
Really, there are good reasons for this: string-based exceptions did not support
categories, state information, or behavior inheritance in the way class-based exceptions do. |
In practice, this made string-based exceptions easier to use at first,
when programs were small, but more complex to use as programs grew larger.
**|**
-----
-----
###### CHAPTER 35
### Designing with Exceptions
This chapter rounds out this part of the book with a collection of exception design
topics and common ... |
For that matter, what does it mean if a
```
try calls a function that runs another try? |
Technically, try statements can nest, in terms
```
of syntax and the runtime control flow through your code.
Both of these cases can be understood if you realize that Python stacks `try statements`
at runtime. |
When an exception is raised, Python returns to the most recently entered
```
try statement with a matching except clause. |
Because each try statement leaves a
```
marker, Python can jump back to earlier trys by inspecting the stacked markers. |
This
nesting of active handlers is what we mean when we talk about propagating exceptions
up to “higher” handlers—such handlers are simply try statements entered earlier in
the program’s execution flow.
Figure 35-1 illustrates what occurs when try statements with except clauses nest at
runtime. |
The amount of code that goes into a try block can be substantial, and it may
contain function calls that invoke other code watching for the same exceptions. |
When
an exception is eventually raised, Python jumps back to the most recently entered
```
try statement that names that exception, runs that statement’s except clause, and then
```
resumes execution after that try.
Once the exception is caught, its life is over—control does not jump back to all matching trys that na... |
In Figure 35-1, for instance, the raise statement in the function func2 sends control
back to the handler in func1, and then the program continues within func1.
-----
_Figure 35-1. |
Nested try/except statements: when an exception is raised (by you or by Python), control_
_jumps back to the most recently entered try statement with a matching except clause, and the program_
_resumes after that try statement. |
except clauses intercept and stop the exception—they are where you_
_process and recover from exceptions._
By contrast, when try statements that contain only finally clauses are nested, each
```
finally block is run in turn when an exception occurs—Python continues propagating
```
the exception up to other trys, and ... |
As Figure 35-2 illustrates, the finally clauses do
not kill the exception—they just specify code to be run on the way out of each `try`
during the exception propagation process. |
If there are many try/finally clauses active
when an exception occurs, they will all be run, unless a try/except catches the exception
somewhere along the way.
_Figure 35-2. |
Nested try/finally statements: when an exception is raised here, control returns to the_
_most recently entered try to run its finally statement, but then the exception keeps propagating to all_
_finallys in all active try statements and eventually reaches the default top-level handler, where an_
_error message is prin... |
finally clauses intercept (but do not stop) an exception—they are for actions_
_to be performed “on the way out.”_
In other words, where the program goes when an exception is raised depends entirely
upon where it has been—it’s a function of the runtime flow of control through the script,
not just its syntax. |
The propagation of an exception essentially proceeds backward
through time to try statements that have been entered but not yet exited. |
This propagation stops as soon as control is unwound to a matching except clause, but not as it
passes through finally clauses on the way.
**|**
-----
###### Example: Control-Flow Nesting
Let’s turn to an example to make this nesting concept more concrete. |
The following
module file, nestexc.py, defines two functions. |
action2 is coded to trigger an exception
(you can’t add numbers and sequences), and action1 wraps a call to action2 in a try
handler, to catch the exception:
```
def action2():
print(1 + []) # Generate TypeError
def action1():
try:
action2()
except TypeError: # Most recent matching try
... |
When action2 triggers the TypeError exception, there will
```
be two active try statements—the one in action1, and the one at the top level of the
module file. |
Python picks and runs just the most recent try with a matching except,
which in this case is the try inside action1.
As I’ve mentioned, the place where an exception winds up jumping to depends on the
control flow through the program at runtime. |
Because of this, to know where you will
go, you need to know where you’ve been. In this case, where exceptions are handled
is more a function of control flow than of statement syntax. |
However, we can also nest
exception handlers syntactically—an equivalent case we’ll look at next.
###### Example: Syntactic Nesting
As I mentioned when we looked at the new unified try/except/finally statement in
Chapter 33, it is possible to nest try statements syntactically by their position in your
source code:
``... |
In fact, syntactic nesting works just like the cases sketched
in Figures 35-1 and 35-2; the only difference is that the nested handlers are physically
embedded in a try block, not coded in functions called elsewhere. |
For example, nested
```
finally handlers all fire on an exception, whether they are nested syntactically or by
```
means of the runtime flow through physically separated parts of your code:
```
>>> try:
... |
try:
... raise IndexError
... finally:
... print('spam')
... finally:
... |
print('SPAM')
...
spam
SPAM
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
IndexError
```
See Figure 35-2 for a graphic illustration of this code’s operation; the effect is the same,
but the function logic has been inlined as nested statements here. |
For a more useful
example of syntactic nesting at work, consider the following file, except-finally.py:
```
def raise1(): raise IndexError
def noraise(): return
def raise2(): raise SyntaxError
for func in (raise1, noraise, raise2):
print('\n', func, sep='')
try:
try:
func()
except In... |
This may take a few moments
to digest, but the effect is much like combining an except and a finally clause in a
single try statement in Python 2.5 and later:
```
% python except-finally.py
<function raise1 at 0x026ECA98>
caught IndexError
finally run
<function noraise at 0x026ECA50>
finally run
<function... |
This makes some of the syntactic nesting described in this
section unnecessary, though it still works, may appear in code written prior to Python
2.5 that you may encounter, and can be used as a technique for implementing alternative exception-handling behaviors.
###### Exception Idioms
We’ve seen the mechanics behin... |
Now let’s take a look at some of the other
ways they are typically used.
###### Exceptions Aren’t Always Errors
In Python, all errors are exceptions, but not all exceptions are errors. |
For instance, we
saw in Chapter 9 that file object read methods return an empty string at the end of a
file. |
In contrast, the built-in input function (which we first met in Chapter 3 and deployed in an interactive loop in Chapter 10) reads a line of text from the standard input
stream, `sys.stdin, at each call and raises the built-in` `EOFError at end-of-file. |
(This`
function is known as raw_input in Python 2.6.)
Unlike file methods, this function does not return an empty string—an empty string
from `input means an empty line. |
Despite its name, the` `EOFError exception is just a`
signal in this context, not an error. |
Because of this behavior, unless the end-of-file
should terminate a script, input often appears wrapped in a try handler and nested in
a loop, as in the following code:
```
while True:
try:
line = input() # Read line from stdin
except EOFError:
break # Exit loop at end-of-file
el... |
Python also has a set of built-in exceptions that represent
```
_warnings rather than errors; some of these are used to signal use of deprecated (phased_
out) language features. |
See the standard library manual’s description of built-in exceptions for more information, and consult the warnings module’s documentation for more
on warnings.
**|**
-----
###### Functions Can Signal Conditions with raise
User-defined exceptions can also signal nonerror conditions. |
For instance, a search
routine can be coded to raise an exception when a match is found instead of returning
a status flag for the caller to interpret. |
In the following, the try/except/else exception
handler does the work of an if/else return-value tester:
```
class Found(Exception): pass
def searcher():
if ...success...:
raise Found()
else:
return
try:
searcher()
except Found: # Exception if item was found
...success...
... |
For instance, if all objects are
potentially valid return values, it’s impossible for any return value to signal unusual
conditions. |
Exceptions provide a way to signal results without a return value:
```
class Failure(Exception): pass
def searcher():
if ...success...:
return ...founditem...
else:
raise Failure()
try:
item = searcher()
except Failure:
...report...
else:
...use item here...
```
Because Python... |
As a summary, though, exception processing tools are also commonly used to ensure that system resources are
finalized, regardless of whether an error occurs during processing or not.
**|**
-----
For example, some servers require connections to be closed in order to terminate a
session. |
Similarly, output files may require close calls to flush their buffers to disk, and
input files may consume file descriptors if not closed; although file objects are automatically closed when garbage collected if still open, it’s sometimes difficult to be sure
when that will occur.
The most general and explicit way to... |
As usual, it depends on your programs. Compared to
the try/finally, context managers are more implicit, which runs contrary to Python’s
general design philosophy. |
Context managers are also arguably less general—they are
available only for select objects, and writing user-defined context managers to handle
general termination requirements is more complex than coding a try/finally.
On the other hand, using existing context managers requires less code than using try/
```
finally, ... |
Moreover, the context manager protocol
```
supports entry actions in addition to exit actions. |
Although the try/finally is perhaps
the more widely applicable technique, context managers may be more appropriate
where they are already available, or where their extra complexity is warranted.
###### Debugging with Outer try Statements
You can also make use of exception handlers to replace Python’s default top-leve... |
By wrapping an entire program (or a call to it) in an outer
```
try in your top-level code, you can catch any exception that may occur while your
```
program runs, thereby subverting the default program termination.
In the following, the empty except clause catches any uncaught exception raised while
the program runs... |
To get hold of the actual exception that occurred, fetch the
```
sys.exc_info function call result from the built-in sys module; it returns a tuple whose
```
first two items contain the current exception’s class and the instance object raised (more
on sys.exc_info in a moment):
**|**
-----
```
try:
...run pr... |
It’s
also used when testing other program code, as described in the next section.
###### Running In-Process Tests
You might combine some of the coding patterns we’ve just looked at in a test-driver
application that tests other code within the same process:
```
import sys
log = open('testlog', 'a')
from testapi ... |
Because an uncaught exception in a test case would
normally kill this test driver, you need to wrap test case calls in a try if you want to
continue the testing process after a test fails. |
The empty except catches any uncaught
exception generated by a test case as usual, and it uses sys.exc_info to log the exception
to a file. |
The else clause is run when no exception occurs—the test success case.
Such boilerplate code is typical of systems that test functions, modules, and classes by
running them in the same process as the test driver. |
In practice, however, testing can
be much more sophisticated than this. |
For instance, to test external programs, you
could instead check status codes or outputs generated by program-launching tools such
as os.system and os.popen, covered in the standard library manual (such tools do not
generally raise exceptions for errors in the external programs—in fact, the test cases
may run in parall... |
This is especially useful
when using the empty except clause to catch everything blindly, to determine what was
raised:
```
try:
...
except:
```
_# sys.exc_info()[0:2] are the exception class and instance_
If no exception is being handled, this call it returns a tuple containing three None values.
Otherwise, ... |
As we saw,
though, because in this case you can also get the exception type by fetching the
```
__class__ attribute of the instance obtained with the as clause, sys.exc_info is mostly
```
used by the empty except today:
```
try:
...
except General as instance:
```
_# instance.__class__ is the exception class_... |
A polymorphic
approach like the last example here generally supports future evolution better.
**|**
-----
_Version skew note: In Python 2.6, the older tools_ `sys.exc_type and`
```
sys.exc_value still work to fetch the most recent exception type and
```
value, but they can manage only a single, global excep... |
These two names have been removed in Python 3.0. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.