EXCEPTION HANDLERS

The exception process uses the try statement in two different forms, the tryexceptelse statement and the tryfinally statement. We've already seen a few examples of the first format; the second format provides a simplified operation sequence when you want to act upon an exception, but not actually handle the exception. We'll look at some examples to make it clearer.

try…except…else

The first form of the try statement acts a bit like an if statement in reverse – you embed a block of code which is executed, and then a number of except statements account for exceptions if they occur. The basic format for this first form is:

try:
    BLOCK
except [EXCEPTION [, DATA...]]:
    BLOCK

else:

    BLOCK

The else block is optional.

When the Python ...

Get Perl To Python Migration now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.