12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

finally clauses run on the way out, and else clauses run if no exceptions are encountered.Syntactically, there may be any number of except clauses, but there should beonly one else. Through <strong>Python</strong> 2.4, the finally clause must appear alone (withoutelse or except); it’s really a different statement. As of <strong>Python</strong> 2.5, however, a finallycan appear in the same statement as except and else.Table 27-1. try statement clause formsClause formexcept:except name:except name, value:except (name1, name2):except (name1, name2), value:else:finally:InterpretationCatch all (other) exception types.Catch a specific exception only.Catch the listed exception and its extra data (or instance).Catch any of the listed exceptions.Catch any of the listed exceptions, and get its extra data.Run if no exceptions are raised.Always perform this block.We’ll explore the entries with the extra value part when we meet the raise statement.The first and fourth entries in Table 27-1 are new here:• except clauses that list no exception name (except:) catch all exceptions not previouslylisted in the try statement.• except clauses that list a set of exceptions in parentheses (except (e1, e2, e3):)catch any of the listed exceptions.Because <strong>Python</strong> looks for a match within a given try by inspecting except clausesfrom top to bottom, the parenthesized version is like listing each exception in its ownexcept clause, but the statement body needs to be coded only once. Here’s an exampleof multiple except clauses at work, which demonstrates just how specific yourhandlers can be:try:action( )except NameError:...except IndexError...except KeyError:...except (AttributeError, TypeError, SyntaxError):...else:...In this example, if an exception is raised while the call to the action function is running,<strong>Python</strong> returns to the try, and searches for the first except that names theexception raised. It inspects except clauses from top to bottom and left to right, andThe try/except/else Statement | 583

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!