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 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.