Text
stringlengths
1
9.41k
By this point in the book, you’ve probably seen your share of standard error messages.
They include the exception that was raised, along with a stack _trace—a list of all the lines and functions that were active when the exception occurred._ The error message text here was printed by Python 3.0; it can vary slightly per release, and even per interactive shell.
When coding interactively in the basic shell interface, the filename is just “<stdin>,” meaning the standard input stream.
When working in the IDLE GUI’s interactive shell, the filename is “<pyshell>”, and source lines are displayed, too.
Either way, file line numbers are not very meaningful when there is no file (we’ll see more interesting error messages later in this part of the book): `>>> fetcher(x, 4)` _# Default handler - IDLE GUI interface_ ``` Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> fetcher(x, 4) F...
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 >>> ``` 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. ###### Raising Exceptions So far, we’ve been letting Python raise exceptions for us by making mistakes (on purpose this time!), but our scripts can raise exceptions too—that is, exceptions can be raised by Python or by your progra...
To trigger an exception manually, simply run a raise statement. User-triggered exceptions are caught the same way as those Python raises.
The following may not be the most useful Python code ever penned, but it makes the point: ``` >>> try: ``` `... raise IndexError` _# Trigger exception manually_ ``` ... except IndexError: ...
print('got exception') ... got exception ``` As usual, if they’re not caught, user-triggered exceptions are propagated up to the toplevel default exception handler and terminate the program with a standard error message: ``` >>> raise IndexError Traceback (most recent call last): File "<stdin>", line 1, in ...
As you’ll learn later in this part of the book, you can also define new exceptions of your own that are specific to your programs.
User-defined exceptions are coded with classes, which inherit from a built-in exception class: usually the class named `Exception.
Class-based exceptions allow scripts to build exception` categories, inherit behavior, and have attached state information: `>>> class Bad(Exception):` _# User-defined exception_ ``` ...
pass ... >>> def doomed(): ``` `... raise Bad()` _# Raise an instance_ ``` ... >>> try: ... doomed() ``` `... except Bad:` _# Catch class name_ ``` ...
print('got Bad') ... got Bad >>> ###### Termination Actions ``` Finally, `try statements can say “finally”—that is, they may include` `finally blocks.` These look like except handlers for exceptions, but the try/finally combination specifies termination actions that always execute “on the way out,” regardless o...
fetcher(x, 3) ``` `... finally:` _# Termination actions_ ``` ...
print('after fetch') ... 'm' after fetch >>> ``` Here, if the try block finishes without an exception, the finally block will run, and the program will resume after the entire try.
In this case, this statement seems a bit silly—we might as well have simply typed the print right after a call to the function, and skipped the try altogether: ``` fetcher(x, 3) print('after fetch') ``` There is a problem with coding this way, though: if the function call raises an exception, the print will never ...
The try/finally combination avoids this pitfall—when an exception does occur in a try block, finally blocks are executed while the program is being unwound: **|** ----- ``` >>> def after(): ...
try: ... fetcher(x, 4) ... finally: ... print('after fetch') ...
print('after try?') ... >>> after() after fetch Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in after File "<stdin>", line 2, in fetcher IndexError: string index out of range >>> ``` Here, we don’t get the “after try?” message because control does ...
Instead, Python jumps back to run the finally action, and then propagates the exception up to a prior handler (in this case, ``` to the default handler at the top).
If we change the call inside this function so as not to trigger an exception, the finally code still runs, but the program continues after the try: ``` >>> def after(): ... try: ...
fetcher(x, 3) ... finally: ... print('after fetch') ...
print('after try?') ... >>> after() after fetch after try? >>> ``` In practice, try/except combinations are useful for catching and recovering from exceptions, and try/finally combinations come in handy to guarantee that termination actions will fire regardless of any exceptions that may occur in the try blo...
We’ll see some such practical examples later in this part of the book. Although they serve conceptually distinct purposes, as of Python 2.5, we can now mix ``` except and finally clauses in the same try statement—the finally is run on the way ``` out regardless of whether an exception was raised, and regardless of wh...
The with/as statement runs an object’s con ``` text management logic to guarantee that termination actions occur: **|** ----- `>>> with open('lumberjack.txt', 'w') as file:` _# Always close file on exit_ ``` ...
file.write('The larch!\n') ``` Although this option requires fewer lines of code, it’s only applicable when processing certain object types, so try/finally is a more general termination structure.
On the other hand, with/as may also run startup actions and supports user-defined context management code. ###### Why You Will Care: Error Checks One way to see how exceptions are useful is to compare coding styles in Python and languages without exceptions.
For instance, if you want to write robust programs in the C language, you generally have to test return values or status codes after every operation that could possibly go astray, and propagate the results of the tests as your programs run: ``` doStuff() { # C program if (doFirstThing() ==...
But in Python, you don’t have to be so methodical (and neurotic!). You can instead wrap arbitrarily vast pieces of a program in exception handlers and simply write the parts that do the actual work, assuming all is well: ``` def doStuff(): # Python code doFirstThing() # We don't care about exceptions here...
They may be raised by Python, or by your own programs. In both cases, they may be ignored (to trigger the default error message), or caught by try statements (to be processed by your code).
The try statement comes in two logical formats that, as of Python 2.5, can be combined—one that handles exceptions, and one that executes finalization code regardless of whether exceptions occur or not.
Python’s `raise and` `assert statements` trigger exceptions on demand (both built-ins and new exceptions we define with classes); the with/as statement is an alternative way to ensure that termination actions are carried out for objects that support it. In the rest of this part of the book, we’ll fill in some of the d...
The next chapter begins our tour by taking a closer look at the statements we introduced here.
Before you turn the page, though, here are a few quiz questions to review. ###### Test Your Knowledge: Quiz 1. Name three things that exception processing is good for. 2.
What happens to an exception if you don’t do anything special to handle it? 3. How can your script recover from an exception? 4. Name two ways to trigger exceptions in your script. 5.
Name two ways to specify actions to be run at termination time, whether an exception occurs or not. ###### Test Your Knowledge: Answers 1.
Exception processing is useful for error handling, termination actions, and event notification.
It can also simplify the handling of special cases and can be used to implement alternative control flows.
In general, exception processing also cuts **|** ----- down on the amount of error-checking code your program may require—because all errors filter up to handlers, you may not need to test the outcome of every operation. 2.
Any uncaught exception eventually filters up to the default exception handler Python provides at the top of your program. This handler prints the familiar error message and shuts down your program. 3.
If you don’t want the default message and shutdown, you can code `try/except` statements to catch and recover from exceptions that are raised.
Once an exception is caught, the exception is terminated and your program continues. 4.
The raise and assert statements can be used to trigger an exception, exactly as if it had been raised by Python itself.
In principle, you can also raise an exception by making a programming mistake, but that’s not usually an explicit goal! 5.
The try/finally statement can be used to ensure actions are run after a block of code exits, regardless of whether it raises an exception or not.
The with/as statement can also be used to ensure termination actions are run, but only when processing object types that support it. **|** ----- ###### CHAPTER 33 ### Exception Coding Details In the prior chapter we took a quick look at exception-related statements in action. Here, we’re going to dig a bit deeper—...
Specifically, we’ll explore the details behind the try, raise, assert, and with statements.
As we’ll see, although these statements are mostly straightforward, they offer powerful tools for dealing with exceptions in Python code. One procedural note up front: The exception story has changed in major ways in recent years.
As of Python 2.5, the finally clause can appear in the same `try statement as` `except and` `else clauses (previously, they` could not be combined).
Also, as of Python 3.0 and 2.6, the new with context manager statement has become official, and user-defined exceptions must now be coded as class instances, which should inherit from a built-in exception superclass.
Moreover, 3.0 sports slightly modified syntax for the raise statement and except clauses.
I will focus on the state of exceptions in Python 2.6 and 3.0 in this edition, but because you are still very likely to see the original techniques in code for some time to come, along the way I’ll point out how things have evolved in this domain. ###### The try/except/else Statement Now that we’ve seen the basics, i...
In the following discussion, I’ll first present `try/except/else and` `try/finally as separate statements, because in` versions of Python prior to 2.5 they serve distinct roles and cannot be combined.
As mentioned in the preceding note, in Python 2.5 and later except and finally can be mixed in a single try statement; I’ll explain the implications of this change after we’ve explored the two original forms in isolation. The try is a compound statement; its most complete form is sketched below.
It starts with a try header line, followed by a block of (usually) indented statements, then one ----- or more except clauses that identify exceptions to be caught, and an optional else clause at the end.
The words try, except, and else are associated by indenting them to the same level (i.e., lining them up vertically).
For reference, here’s the general format in Python 3.0: ``` try: <statements> # Run this main action first except <name1>: ``` `<statements> # Run if` `name1` _is raised during try block_ ``` except (name2, name3): <statements> # Run if any of these exceptions occur except <name4> as <da...
The except clauses define handlers for exceptions raised during the try block, and the else clause (if coded) provides a handler to be run if no exceptions occur.
The `<data> entry here has to do with a feature of` ``` raise statements and exception classes, which we will discuss later in this chapter. ``` Here’s how try statements work.
When a try statement is entered, Python marks the current program context so it can return to it if an exception occurs. The statements nested under the `try header are run first.
What happens next depends on whether` exceptions are raised while the try block’s statements are running: - If an exception does occur while the try block’s statements are running, Python jumps back to the try and runs the statements under the first except clause that matches the raised exception.
Control resumes below the entire try statement after the except block runs (unless the except block raises another exception). - If an exception happens in the try block and no `except clause matches, the excep-` tion is propagated up to the last matching try statement that was entered in the program or, if it’s the ...
However, as the try block’s statements can call functions coded elsewhere in a program, the source of an exception may be outside the try statement itself.
I’ll have more to say about this when we explore ``` try nesting in Chapter 35. ``` **|** ----- ###### 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 ...
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). _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,...
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. _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. ###### The try else Clause ``` The purpose of the else clause is not always immediately obvious to Python newcomers.
Without it, though, there is no way to tell (without setting and checking Boolean flags) whether the flow of control has proceeded past a try statement because no exception was raised, or because an exception occurred and was handled: ``` try: ...run code... except IndexError: ...handle exception... ``` _#...
If the “no exception occurred” action triggers an IndexError, it will register as a failure of the try block and **|** ----- erroneously trigger the exception handler below the try (subtle, but true!).
By using an explicit `else clause instead, you make the logic more obvious and guarantee that` ``` except handlers will run only for real failures in the code you’re wrapping in a try, not ``` for failures in the else case’s action. ###### Example: Default Behavior Because the control flow through a program is easie...
I’ve mentioned that exceptions not caught by try statements percolate up to the top level of the Python process and run Python’s default exception-handling logic (i.e., Python terminates the running program and prints a standard error message).
Let’s look at an example.
Running the following module file, bad.py, generates a divide-by-zero exception: ``` def gobad(x, y): return x / y def gosouth(x): print(gobad(x, 0)) gosouth(1) ``` Because the program ignores the exception it triggers, Python kills the program and prints a message: ``` % python bad.py Traceback (mos...