预计阅读本页时间:-
Exception Roles
In Python programs, exceptions are typically used for a variety of purposes. Here are some of their most common roles:
Error handling
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
Python raises exceptions whenever it detects errors in programs at runtime. You can catch and respond to the errors in your code, or ignore the exceptions that are raised. If an error is ignored, Python’s default exception-handling behavior kicks in: it stops the program and prints an error message. If you don’t want this default behavior, code a try statement to catch and recover from the exception—Python will jump to your try handler when the error is detected, and your program will resume execution after the try.
Event notification
Exceptions can also be used to signal valid conditions without you having to pass result flags around a program or test them explicitly. For instance, a search routine might raise an exception on failure, rather than returning an integer result code (and hoping that the code will never be a valid result).
Special-case handling
Sometimes a condition may occur so rarely that it’s hard to justify convoluting your code to handle it. You can often eliminate special-case code by handling unusual cases in exception handlers in higher levels of your program.
Termination actions
As you’ll see, the try/finally statement allows you to guarantee that required closing-time operations will be performed, regardless of the presence or absence of exceptions in your programs.
Unusual control flows
Finally, because exceptions are a sort of high-level “go to,” you can use them as the basis for implementing exotic control flows. For instance, although the language does not explicitly support backtracking, it can be implemented in Python by using exceptions and a bit of support logic to unwind assignments.[73] There is no “go to” statement in Python (thankfully!), but exceptions can sometimes serve similar roles.
We’ll see such typical use cases in action later in this part of the book. For now, let’s get started with a look at Python’s exception-processing tools.
[73] True backtracking is an advanced topic that is not part of the Python language, so I won’t say much more about it here (even the generator functions and expressions we met in Chapter 20 are not true backtracking—they simply respond to next(G) requests). Roughly, backtracking undoes all computations before it jumps; Python exceptions do not (i.e., variables assigned between the time a try statement is entered and the time an exception is raised are not reset to their prior values). See a book on artificial intelligence or the Prolog or Icon programming languages if you’re curious.