预计阅读本页时间:-
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:
try:
try:
action2()
except TypeError: # Most recent matching try
print('inner try')
except TypeError: # Here, only if nested handler re-raises
print('outer try')
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
Really, this code just sets up the same handler-nesting structure as (and behaves identically to) the prior example. 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 IndexError:
print('caught IndexError')
finally:
print('finally run')
This code catches an exception if one is raised and performs a finally termination-time action regardless of whether an exception occurs. 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 raise2 at 0x026ECBB8>
finally run
Traceback (most recent call last):
File "except-finally.py", line 9, in <module>
func()
File "except-finally.py", line 3, in raise2
def raise2(): raise SyntaxError
SyntaxError: None
As we saw in Chapter 33, as of Python 2.5, except and finally clauses can be mixed in the same try statement. 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.