Text
stringlengths
1
9.41k
Before we move ahead, though, let’s work though the following short quiz on the basics covered here. ###### Test Your Knowledge: Quiz 1. What is the try statement for? 2.
What are the two common variations of the try statement? 3. What is the raise statement for? 4. What is the assert statement designed to do, and what other statement is it like? 5.
What is the with/as statement designed to do, and what other statement is it like? ###### Test Your Knowledge: Answers 1.
The try statement catches and recovers from exceptions—it specifies a block of code to run, and one or more handlers for exceptions that may be raised during the block’s execution. 2.
The two common variations on the try statement are try/except/else (for catching exceptions) and `try/finally (for specifying cleanup actions that must occur` whether an exception is raised or not).
In Python 2.4, these were separate statements that could be combined by syntactic nesting; in 2.5 and later, except and ``` finally blocks may be mixed in the same statement, so the two statement forms ``` are merged.
In the merged form, the finally is still run on the way out of the try, regardless of what exceptions may have been raised or handled. 3. The raise statement raises (triggers) an exception.
Python raises built-in exceptions on errors internally, but your scripts can trigger built-in or user-defined exceptions with raise, too. 4.
The assert statement raises an AssertionError exception if a condition is false. It works like a conditional raise statement wrapped up in an if statement. 5.
The with/as statement is designed to automate startup and termination activities that must occur around a block of code.
It is roughly like a try/finally statement in that its exit actions run whether an exception occurred or not, but it allows a richer object-based protocol for specifying entry and exit actions. **|** ----- ###### CHAPTER 34 ### Exception Objects So far, I’ve been deliberately vague about what an exception actually...
As suggested in the prior chapter, in Python 2.6 and 3.0 both built-in and user-defined exceptions are identified by _class instance objects.
Although this means you must use object-_ oriented programming to define new exceptions in your programs, classes and OOP in general offer a number of benefits. Here are some of the advantages of class-based exceptions: - They can be organized into categories.
Exception classes support future changes by providing categories—adding new exceptions in the future won’t generally require changes in try statements. - They have attached state information.
Exception classes provide a natural place for us to store context information for use in the try handler—they may have both attached state information and callable methods, accessible through instances. - They support inheritance.
Class-based exceptions can participate in inheritance hierarchies to obtain and customize common behavior—inherited display methods, for example, can provide a common look and feel for error messages. Because of these advantages, class-based exceptions support program evolution and larger systems well.
In fact, all built-in exceptions are identified by classes and are organized into an inheritance tree, for the reasons just listed.
You can do the same with user-defined exceptions of your own. In Python 3.0, user-defined exceptions inherit from built-in exception superclasses.
As we’ll see here, because these superclasses provide useful defaults for printing and state retention, the task of coding user-defined exceptions also involves understanding the roles of these built-ins. ----- _Version skew note: Python 2.6 and 3.0 both require exceptions to be_ defined by classes.
In addition, 3.0 requires exception classes to be derived from the `BaseException built-in exception superclass, either di-` rectly or indirectly.
As we’ll see, most programs inherit from this class’s ``` Exception subclass, to support catchall handlers for normal exception ``` types—naming it in a handler will catch everything most programs should.
Python 2.6 allows standalone classic classes to serve as exceptions, too, but it requires new-style classes to be derived from built-in exception classes, the same as 3.0. ###### Exceptions: Back to the Future Once upon a time (well, prior to Python 2.6 and 3.0), it was possible to define exceptions in two different ...
This complicated try statements, raise statements, and Python in general. Today, there is only one way to do it.
This is a good thing: it removes from the language substantial cruft accumulated for the sake of backward compatibility.
Because the old way helps explain why exceptions are as they are today, though, and because it’s not really possible to completely erase the history of something that has been used by a million people over the course of nearly two decades, let’s begin our exploration of the present with a brief look at the past. #####...
String-based exceptions began issuing deprecation warnings in 2.5 and were removed in 2.6 and 3.0, so today you should use class-based exceptions, as shown in this book.
If you work with legacy code, though, you might still come across string exceptions.
They might also appear in tutorials and web resources written a few years ago (which qualifies as an eternity in Python years!). String exceptions were straightforward to use—any string would do, and they matched by object identity, not value (that is, using is, not ==): ``` C:\misc> C:\Python25\python ``` `>>> mye...
raise myexc ... except myexc: ... print('caught') ... caught ``` This form of exception was removed because it was not as good as classes for larger programs and code maintenance.
Although you can’t use string exceptions today, they actually provide a natural vehicle for introducing the class-based exceptions model. **|** ----- ###### Class-Based Exceptions Strings were a simple way to define exceptions.
As described earlier, however, classes have some added advantages that merit a quick look.
Most prominently, they allow us to identify exception categories that are more flexible to use and maintain than simple strings.
Moreover, classes naturally allow for attached exception details and support inheritance.
Because they are the better approach, they are now required. Coding details aside, the chief difference between string and class exceptions has to do with the way that exceptions raised are matched against `except clauses in` `try` statements: - String exceptions were matched by simple object identity: the raised ex...
The net effect is that class exceptions support the construction of exception hierarchies: superclasses become category names, and subclasses become specific kinds of exceptions within a category.
By naming a general exception superclass, an except clause can catch an entire category of exceptions—any more specific subclass will match. String exceptions had no such concept: because they were matched by simple object identity, there was no direct way to organize exceptions into more flexible categories or groups...
The net result was that exception handlers were coupled with exception sets in a way that made changes difficult. In addition to this category idea, class-based exceptions better support exception state _information (attached to instances) and allow exceptions to participate in inheritance_ _hierarchies (to obtain com...
Because they offer all the benefits of classes_ and OOP in general, they provide a more powerful alternative to the now defunct stringbased exceptions model in exchange for a small amount of additional code. ###### Coding Exceptions Classes Let’s look at an example to see how class exceptions translate to code.
In the following file, _classexc.py, we define a superclass called_ `General and two subclasses called` ``` Specific1 and Specific2.
This example illustrates the notion of exception categories— General is a category name, and its two subclasses are specific types of exceptions within ``` the category.
Handlers that catch General will also catch any subclasses of it, including ``` Specific1 and Specific2: class General(Exception): pass class Specific1(General): pass ``` **|** ----- ``` class Specific2(General): pass def raiser0(): X = General() # Raise superclass instance raise X def raiser1...
Notice, though, how the top-level class here inherits from the built-in Exception class. This is required in Python 3.0; Python 2.6 allows standalone classic classes to serve as exceptions too, but it requires new-style classes to be derived from built-in exception classes just like in 3.0.
Although we don’t employ it here, because ``` Exception provides some useful behavior we’ll meet later, it’s a good idea to inherit ``` from it in either Python. _Raising instances_ In this code, we call classes to make instances for the raise statements.
In the class exception model, we always raise and catch a class instance object.
If we list a class name without parentheses in a raise, Python calls the class with no constructor argument to make an instance for us.
Exception instances can be created before the raise, as done here, or within the raise statement itself. _Catching categories_ This code includes functions that raise instances of all three of our classes as exceptions, as well as a top-level `try that calls the functions and catches` `General` exceptions.
The same try also catches the two specific exceptions, because they are subclasses of General. **|** ----- _Exception details_ The exception handler here uses the sys.exc_info call—as we’ll see in more detail in the next chapter, it’s how we can grab hold of the most recently raised exception in a generic fashion.
Briefly, the first item in its result is the class of the exception raised, and the second is the actual instance raised.
In a general except clause like the one here that catches all classes in a category, sys.exc_info is one way to determine exactly what’s occurred.
In this particular case, it’s equivalent to fetching the instance’s `__class__ attribute.
As we’ll see in the next chapter, the` ``` sys.exc_info scheme is also commonly used with empty except clauses that catch ``` everything. The last point merits further explanation.
When an exception is caught, we can be sure that the instance raised is an instance of the class listed in the except, or one of its more specific subclasses.
Because of this, the __class__ attribute of the instance also gives the exception type.
The following variant, for example, works the same as the prior example: ``` class General(Exception): pass class Specific1(General): pass class Specific2(General): pass def raiser0(): raise General() def raiser1(): raise Specific1() def raiser2(): raise Specific2() for func in (raiser0, raiser1, raiser2)...
Furthermore, more realistic programs usually should not have to care about which specific exception was raised at all—by calling methods of the instance generically, we automatically dispatch to behavior tailored for the exception raised.
More on this and `sys.exc_info in the next chapter; also see` Chapter 28 and Part VI at large if you’ve forgotten what __class__ means in an instance. ###### Why Exception Hierarchies? Because there are only three possible exceptions in the prior section’s example, it doesn’t really do justice to the utility of class...
In fact, we could achieve the same effects by coding a list of exception names in parentheses within the except clause: ``` try: func() except (General, Specific1, Specific2): # Catch any of these ... ``` **|** ----- This approach worked for the defunct string exception model too.
For large or high exception hierarchies, however, it may be easier to catch categories using class-based categories than to list every member of a category in a single except clause.
Perhaps more importantly, you can extend exception hierarchies by adding new subclasses without breaking existing code. Suppose, for example, you code a numeric programming library in Python, to be used by a large number of people.
While you are writing your library, you identify two things that can go wrong with numbers in your code—division by zero, and numeric overflow. You document these as the two exceptions that your library may raise: _# mathlib.py_ ``` class Divzero(Exception): pass class Oflow(Exception): pass def func(): ... ...
Six months down the road, though, you revise it (as programmers are prone to do).
Along the way, you identify a new thing that can go wrong—underflow—and add that as a new exception: _# mathlib.py_ ``` class Divzero(Exception): pass class Oflow(Exception): pass class Uflow(Exception): pass ``` Unfortunately, when you re-release your code, you create a maintenance problem for your users.
If they’ve listed your exceptions explicitly, they now have to go back and change every place they call your library to include the newly added exception name: _# client.py_ ``` try: mathlib.func(...) except (mathlib.Divzero, mathlib.Oflow, mathlib.Uflow): ...handle and recover... ``` **|** ----- This ...
If your library is used only in-house, you can make the changes yourself.
You might also ship a Python script that tries to fix such code automatically (it would probably be only a few dozen lines, and it would guess right at least some of the time).
If many people have to change all their try statements each time you alter your exception set, though, this is not exactly the most polite of upgrade policies. Your users might try to avoid this pitfall by coding empty except clauses to catch all possible exceptions: _# client.py_ ``` try: mathlib.func(...) e...
As a rule of thumb, it’s usually better to be specific than general in exception handlers—an idea we’ll revisit as a “gotcha” in the next chapter.[*] So what to do, then?
Class exception hierarchies fix this dilemma completely.
Rather than defining your library’s exceptions as a set of autonomous classes, arrange them into a class tree with a common superclass to encompass the entire category: _# mathlib.py_ ``` class NumErr(Exception): pass class Divzero(NumErr): pass class Oflow(NumErr): pass ... def func(): ... raise Div...
When new exceptions are added later, the library can just expand the exported tuple._ This would work, but you’d still need to keep the tuple up-to-date with raised exceptions inside the library module.
Also, class hierarchies offer more benefits than just categories—they also support inherited state and methods and a customization model that individual exceptions do not. **|** ----- _# client.py_ ``` import mathlib ... try: mathlib.func(...) except mathlib.NumErr: ...report and recover... ``` Whe...
In fact, you are free to add, delete, and change exceptions arbitrarily in the_ future—as long as clients name the superclass, they are insulated from changes in your exceptions set.
In other words, class exceptions provide a better answer to maintenance issues than strings do. Class-based exception hierarchies also support state retention and inheritance in ways that make them ideal in larger programs.
To understand these roles, though, we first need to see how user-defined exception classes relate to the built-in exceptions from which they inherit. ###### Built-in Exception Classes I didn’t really pull the prior section’s examples out of thin air.
All built-in exceptions that Python itself may raise are predefined class objects.
Moreover, they are organized into a shallow hierarchy with general superclass categories and specific subclass types, much like the exceptions class tree we developed earlier. In Python 3.0, all the familiar exceptions you’ve seen (e.g., SyntaxError) are really just predefined classes, available as built-in names in t...
In addition, Python organizes the built-in exceptions into a hierarchy, to support a variety of catching modes. For example: ``` BaseException ``` The top-level root superclass of exceptions.
This class is not supposed to be directly inherited by user-defined classes (use Exception instead). It provides default printing and state retention behavior inherited by subclasses.
If the str built-in is called on an instance of this class (e.g., by print), the class returns the display strings of the constructor arguments passed when the instance was created (or an empty string if there were no arguments).
In addition, unless subclasses replace this class’s **|** ----- constructor, all of the arguments passed to this class at instance construction time are stored in its args attribute as a tuple. ``` Exception ``` The top-level root superclass of application-related exceptions.
This is an immediate subclass of BaseException and is superclass to every other built-in exception, except the system exit event classes (SystemExit, `KeyboardInterrupt, and` ``` GeneratorExit).
Almost all user-defined classes should inherit from this class, not BaseException.
When this convention is followed, naming Exception in a try state ``` ment’s handler ensures that your program will catch everything but system exit events, which should normally be allowed to pass.
In effect, Exception becomes a catchall in try statements and is more accurate than an empty except. ``` ArithmeticError ``` The superclass of all numeric errors (and a subclass of Exception). ``` OverflowError ``` A subclass of ArithmeticError that identifies a specific numeric error. And so on—you can read further...
Note that the exceptions class tree dif-_ fers slightly between Python 3.0 and 2.6.
Also note that you can see the class tree in the help text of the exceptions module in Python 2.6 only (this module is removed in 3.0). See Chapters 4 and 15 for help on help: ``` >>> import exceptions >>> help(exceptions) ...lots of text omitted... ###### Built-in Exception Categories ``` The built-in class tr...
For example, the built-in exception ArithmeticError is a superclass for more specific exceptions such as OverflowError and ZeroDivisionError.
By listing ArithmeticError in a `try, you will catch any kind of numeric error raised; by listing just` ``` OverflowError, you will intercept just that specific type of error, and no others. ``` Similarly, because Exception is the superclass of all application-level exceptions in Python 3.0, you can generally use it a...
This technique is more reliable in Python 3.0, since it requires all ``` classes to derive from built-in exceptions.
Even in Python 3.0, though, this scheme suffers most of the same potential pitfalls as the empty except, as described in the prior chapter—it might intercept exceptions intended for elsewhere, and it might mask genuine programming errors.
Since this is such a common issue, we’ll revisit it as a “gotcha” in the next chapter. Whether or not you will leverage the categories in the built-in class tree, it serves as a good example; by using similar techniques for class exceptions in your own code, you can provide exception sets that are flexible and easily ...
Unless you redefine the constructors your classes inherit from them, any constructor arguments you pass to these classes are saved in the instance’s args tuple attribute and are automatically displayed when the instance is printed (an empty tuple and display string are used if no constructor arguments are passed). Thi...
raise E('spam') ... except E as X: ``` `... print(X, X.args)` _# Displays and saves constructor arguments_ ``` ... spam ('spam',) ``` **|** ----- ``` >>> try: ...
raise E('spam', 'eggs', 'ham') ... except E as X: ...
print(X, X.args) ... ('spam', 'eggs', 'ham') ('spam', 'eggs', 'ham') ``` Note that exception instance objects are not strings themselves, but use the __str__ operator overloading protocol we studied in Chapter 29 to provide display strings when printed; to concatenate with real strings, perform manual conversions:...
raise MyBad('Sorry--my mistake!') ... except MyBad as X: ...
print(X) ... Sorry--my mistake! ``` This inherited default display model is also used if the exception is displayed as part of an error message when the exception is not caught: ``` >>> raise MyBad('Sorry--my mistake!') Traceback (most recent call last): File "<stdin>", line 1, in <module> __main__.MyBad:...
To provide a more custom display, though, you can define one of two string-representation overloading methods in your class (__repr__ or ``` __str__) to return the string you want to display for your exception.
The string the ``` method returns will be displayed if the exception either is caught and printed or reaches the default handler: ``` >>> class MyBad(Exception): ... def __str__(self): ...
return 'Always look on the bright side of life...' ... >>> try: ... raise MyBad() ... except MyBad as X: ...