[ Team LiB ] |
26.4 Exception GotchasThere isn't much to trip over with exceptions, but here are two general pointers on use, one of which summarizes concepts we've already met. 26.4.1 String Exceptions Match by Identity, Not ValueWhen an exception is raised (by you or by Python itself), Python searches for the most recently entered try statement with a matching except clause, where matching means the same string object, the same class, or a superclass of the raised class. It's important to notice that matching is performed by identity, not equality. For instance, suppose we define two string objects we want to raise as exceptions: >>> ex1 = 'Error: Spam Exception' >>> ex2 = 'Error: Spam Exception' >>> >>> ex1 == ex2, ex1 is ex2 (1, 0) Applying the == test returns true (1) because they have equal values, but is returns false (0) since they are two distinct string objects in memory. Now, an except clause that names the same string object will always match: >>> try: ... raise ex1 ... except ex1: ... print 'got it' ... got it But one that lists an equal value, but not an identical object, will fail (assuming the string values are long enough to defeat Python's string object caching mechanism, which is described in Chapter 4 and Chapter 7: >>> try: ... raise ex1 ... except ex2: ... print 'Got it' ... Traceback (innermost last): File "<stdin>", line 2, in ? raise ex1 Error: Spam Exception Here, the exception isn't caught, so Python climbs to the top level of the process and prints a stack trace and the exception's text automatically. For strings, be sure to use the same object in the raise and the try. For class exceptions, the behavior is similar, but Python generalizes the notion of exception matching to include superclass relationships. 26.4.2 Catching the Wrong ThingPerhaps the most common gotchas related to exceptions involve the design guidelines of the prior section. Remember, try to avoid empty except clauses (or you may catch things like system exits), and overly-specific except clauses (use superclass categories instead, to avoid maintenance issues in the future). |
[ Team LiB ] |