预计阅读本页时间:-
try Statement Clauses
When you write a try statement, a variety of clauses can appear after the try header. Table 33-1 summarizes all the possible forms—you must use at least one. We’ve already met some of these: as you know, except clauses catch exceptions, finally clauses run on the way out, and else clauses run if no exceptions are encountered.
Syntactically, there may be any number of except clauses, but you can code else only if there is at least one except, and there can be only one else and one finally. Through Python 2.4, the finally clause must appear alone (without else or except); the try/finally is really a different statement. As of Python 2.5, however, a finally can appear in the same statement as except and else (more on the ordering rules later in this chapter when we meet the unified try statement).
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
Table 33-1. try statement clause forms
Clause form
Interpretation
except:
Catch all (or all other) exception types.
except name:
Catch a specific exception only.
except name as value:
Catch the listed exception and its instance.
except (name1, name2):
Catch any of the listed exceptions.
except (name1, name2) as value:
Catch any listed exception and its instance.
else:
Run if no exceptions are raised.
finally:
Always perform this block.
We’ll explore the entries with the extra as value part when we meet the raise statement. They provide access to the objects that are raised as exceptions.
The first and fourth entries in Table 33-1 are new here:
- except clauses that list no exception name (except:) catch all exceptions not previously listed in the try statement.
- except clauses that list a set of exceptions in parentheses (except (e1, e2, e3):) catch any of the listed exceptions.
Because Python looks for a match within a given try by inspecting the except clauses from top to bottom, the parenthesized version has the same effect as listing each exception in its own except clause, but you have to code the statement body only once. Here’s an example of multiple except clauses at work, which demonstrates just how specific your handlers can be:
try:
action()
except NameError:
...
except IndexError:
...
except KeyError:
...
except (AttributeError, TypeError, SyntaxError):
...
else:
...
In this example, if an exception is raised while the call to the action function is running, Python returns to the try and searches for the first except that names the exception raised. It inspects the except clauses from top to bottom and left to right, and runs the statements under the first one that matches. If none match, the exception is propagated past this try. Note that the else runs only when no exception occurs in action—it does not run when an exception without a matching except is raised.
If you really want a general “catch-all” clause, an empty except does the trick:
try:
action()
except NameError:
... # Handle NameError
except IndexError:
... # Handle IndexError
except:
... # Handle all other exceptions
else:
... # Handle the no-exception case
The empty except clause is a sort of wildcard feature—because it catches everything, it allows your handlers to be as general or specific as you like. In some scenarios, this form may be more convenient than listing all possible exceptions in a try. For example, the following catches everything without listing anything:
try:
action()
except:
... # Catch all possible exceptions
Empty excepts also raise some design issues, though. Although convenient, they may catch unexpected system exceptions unrelated to your code, and they may inadvertently intercept exceptions meant for another handler. For example, even system exit calls in Python trigger exceptions, and you usually want these to pass. That said, this structure may also catch genuine programming mistakes for you which you probably want to see an error message. We’ll revisit this as a gotcha at the end of this part of the book. For now, I’ll just say “use with care.”
Python 3.0 introduced an alternative that solves one of these problems—catching an exception named Exception has almost the same effect as an empty except, but ignores exceptions related to system exits:
try:
action()
except Exception:
... # Catch all possible exceptions, except exits
This has most of the same convenience of the empty except, but also most of the same dangers. We’ll explore how this form works its voodoo in the next chapter, when we study exception classes.
Note
Version skew note: Python 3.0 requires the except E as V: handler clause form listed in Table 33-1 and used in this book, rather than the older except E, V: form. The latter form is still available (but not recommended) in Python 2.6: if used, it’s converted to the former. The change was made to eliminate errors that occur when confusing the older form with two alternate exceptions, properly coded in 2.6 as except (E1, E2):. Because 3.0 supports the as form only, commas in a handler clause are always taken to mean a tuple, regardless of whether parentheses are used or not, and the values are interpreted as alternative exceptions to be caught. This change also modifies the scoping rules: with the new as syntax, the variable V is deleted at the end of the except block.