预计阅读本页时间:-
Catching Exceptions
Sometimes, this isn’t what you want, though. Server programs, for instance, typically need to remain active even after internal errors. If you don’t want the default exception behavior, wrap the call in a try statement to catch exceptions yourself:
>>> try:
... fetcher(x, 4)
... except IndexError: # Catch and recover
... print('got exception')
...
got exception
>>>
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
Now, Python jumps to your handler (the block under the except clause that names the exception raised) automatically when an exception is triggered while the try block is running. When working interactively like this, after the except clause runs, we wind up back at the Python prompt. In a more realistic program, try statements not only catch exceptions, but also recover from them:
>>> def catcher():
... try:
... fetcher(x, 4)
... except IndexError:
... print('got exception')
... print('continuing')
...
>>> catcher()
got exception
continuing
>>>
This time, after the exception is caught and handled, the program resumes execution after the entire try statement that caught it—which is why we get the “continuing” message here. We don’t see the standard error message, and the program continues on its way normally.