In this concluding article of the Python 101 series, find out howto use Python's exception-handling routines to trap and resolve programerrors, learn to generate and use custom error messages, and get acquainteda bunch of useful (and free!) Python resources online.
Python offers two flavours of exception handler - the first is the"try-except" construct you just saw, while the second is the "try-finally"construct.
The "try-except" construct - actually the "try-except-else" construct -allows developers to trap different types of errors and execute appropriateexception-handling code depending on the exception type. It's a lot likethe "if-elif-else" conditional construct, allowing for the execution ofdifferent code blocks depending on the type of error generated.
The structure of a "try-except-else" block looks like this:
try:
execute this block
except err1:
execute this block if exception "err1" is generated
except err2:
execute this block if exception "err2" is generated
... and so on ...
else:
execute this block
When Python encounters code wrapped within a "try-except-else" block, itfirst attempts to execute the code within the "try" block. If this code isprocessed without any exceptions being generated, Python checks to see ifthe optional "else" block is present. If it is, the code within it isexecuted.
If an exception is encountered while running the code within the "try"block, Python stops execution of the "try" block at that point and beginschecking each "except" block to see if there is a handler for theexception. If a handler is found, the code within the appropriate "except"block is executed; if not, control either moves to the parent "try" block,if one exists, or to the default handler, which terminates the program anddisplays a stack trace.
Once the "try" block has been executed and assuming that the program hasnot been terminated, the lines following the "try" block are executed.
Let's illustrate this with a simple Python program, which accepts twonumbers and attempts to divide them by each other.
Now look what happens when I run this with different values.
Gimme a number: 10
Gimme another number: 2
10 divided by 2 is 5
Gimme a number: 10
Gimme another number: 0
Traceback (innermost last):
File "div.py", line 6, in ?
gamma = alpha / beta
ZeroDivisionError: integer division or modulo
Gimme a number: 67347328
Gimme another number: 943282646373739
Traceback (innermost last):
File "div.py", line 4, in ?
beta = input("Gimme another number: ")
OverflowError: integer literal too large
Let's now add a couple of exception handlers to this code, so that it knowshow to gracefully handle errors like the ones above:
#!/usr/bin/python
try:
alpha = input("Gimme a number: ")
beta = input("Gimme another number: ")
gamma = alpha / beta
print alpha, "divided by", beta, "is", gamma
except ZeroDivisionError:
print "Cannot divide by zero!"
except OverflowError:
print "Number too large!"
else:
print "No errors encountered!"
print "-- All done --"
And now let's try the different test cases above again:
Gimme a number: 10
Gimme another number: 2
10 divided by 2 is 5
No errors encountered!
-- All done --
Gimme a number: 10
Gimme another number: 0
Cannot divide by zero!
-- All done --
Gimme a number: 823748237
Gimme another number: 234378264732647326476327
Number too large!
-- All done --
Depending on the type of error encountered, the appropriate exceptionhandler is triggered and an error message displayed. The optional "else"block is executed at the end of the script *only* if no exceptions areencountered.
Once an exception has been caught and resolved, the remainder of the "try"block is ignored and Python executes the lines following the entire"try-except-else" block.