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 ...
Get Learning Python now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.