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.
Most of what you've just learned also applies to Python's otherexception-handlng construct, the "try-finally" statement. The "try-finally"statement block differs from "try-except-else" in that it merely detectserrors; it does not provide for a mechanism to resolve them. It istypically used to ensure that certain statements are always executed whenan error (regardless of type) is encountered.
The "try-finally" statement block looks like this:
execute this block
if exceptions generated, execute this block
If an exception is encountered when running the code within the "try"block, Python will stop execution at that point; jump to the "finally"block; execute the statements within it; and then pass the exceptionupwards, to the parent "try" block, if one exists, or to the defaulthandler, which terminates the program and displays a stack trace.
# generate error by accessing index out of range
print "Something bad happened"
When this program runs, an IndexError exception will be generated and the"finally" block will execute, printing an error message. Control will thenflow to the parent exception handler, which is the Python interpreter inthis case; the interpreter will terminate the program and print a stacktrace.
Something bad happened
Traceback (innermost last):
File "dessert.py", line 7, in ?
IndexError: tuple index out of range
Since "try-finally" blocks simply detect errors, passing the resolutionbuck upwards to the parent "try" block, it's possible to nest them within"try-except-else" blocks. Take a look: