Skip to Main Content
Learning Python
book

Learning Python

by Mark Lutz, David Ascher
April 1999
Beginner content levelBeginner
384 pages
11h 15m
English
O'Reilly Media, Inc.
Content preview from Learning Python

Exception Idioms

We’ve seen the mechanics behind exceptions; now, let’s take look at some of the ways they’re typically used.

Exceptions Aren’t Always a Bad Thing

Python raises exceptions on errors, but not all exceptions are errors. For instance, we saw in Chapter 2, that file object read methods return empty strings at the end of a file. Python also provides a built-in function called raw_input for reading from the standard input stream; unlike file methods, raw_input raises the built-in EOFError at end of file, instead of returning an empty string (an empty string means an empty line when raw_input is used). Because of that, raw_input often appears wrapped in a try handler and nested in a loop, as in the following code

while 1:
    try:
        line = raw_input()     # read line from stdin
    except EOFError:
        break                  # exit loop at end of file
    else:
            Process next 'line' here

Searches Sometimes Signal Success by raise

User-defined exceptions can signal nonerror conditions also. For instance, a search routine can be coded to raise an exception when a match is found, instead of returning a status flag that must be interpreted by the caller. In the following, the try/except/else exception handler does the work of an if/else return value tester:

Found = "Item found"

def searcher():
    raise Found or return
try:
    searcher()
except Found:              # exception if item was found
    Success
else:                      # else returned: not found
    Failure

Outer try Statements Can Debug Code

You can also make use of exception handlers to replace Python’s ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Python

Learning Python

Fabrizio Romano
Getting Started with Python

Getting Started with Python

Fabrizio Romano, Benjamin Baka, Dusty Phillips

Publisher Resources

ISBN: 1565924649Supplemental ContentCatalog PageErrata