Friday 20 July 2018

Python Try Statement

Cited from the book "Python How to Program"

Python uses try statements to enable exception handling. The try statement
encloses other statements that potentially cause exceptions. A try statement begins with
keyword try, followed by a colon (:), followed by a suite of code in which exceptions
may occur. The try statement may specify one or more except clauses that immediately
follow the try suite. Each except clause specifies zero or more exception class names
that represent the type(s) of exceptions that the except clause can handle. An except
clause (also called an except handler) also may specify an identifier that the program can
use to reference the exception object that was caught. The handler can use the identifier to
obtain information about the exception from the exception object. An except clause that
specifies no exception type is called an empty except clause. Such a clause catches all
exception types. After the last except clause, an optional else clause contains code that
executes if the code in the try suite raised no exceptions. If a try statement specifies no
except clauses, the statement must contain a finally clause, which always executes,
regardless of whether an exception occurs. We discuss each possible combination of
clauses over the next several sections.

It is a syntax error to write a try statement that contains except and finally clauses.
The only acceptable forms are try/except, try/except/else and try/finally.


No comments:

Post a Comment