mirror of
https://github.com/python/cpython.git
synced 2025-08-01 23:53:15 +00:00
Clarify the description of the else clause for try/except, and add an
explanation of why you'd want to use it. Based on a question from Michael Simcich <msimcich@accesstools.com>.
This commit is contained in:
parent
eacdea8572
commit
e99d1dbc74
1 changed files with 8 additions and 3 deletions
|
@ -2996,9 +2996,9 @@ except:
|
||||||
\end{verbatim}
|
\end{verbatim}
|
||||||
|
|
||||||
The \keyword{try} \ldots\ \keyword{except} statement has an optional
|
The \keyword{try} \ldots\ \keyword{except} statement has an optional
|
||||||
\emph{else clause}, which must follow all except clauses. It is
|
\emph{else clause}, which, when present, must follow all except
|
||||||
useful to place code that must be executed if the try clause does not
|
clauses. It is useful for code that must be executed if the try
|
||||||
raise an exception. For example:
|
clause does not raise an exception. For example:
|
||||||
|
|
||||||
\begin{verbatim}
|
\begin{verbatim}
|
||||||
for arg in sys.argv[1:]:
|
for arg in sys.argv[1:]:
|
||||||
|
@ -3011,6 +3011,11 @@ for arg in sys.argv[1:]:
|
||||||
f.close()
|
f.close()
|
||||||
\end{verbatim}
|
\end{verbatim}
|
||||||
|
|
||||||
|
The use of the \keyword{else} clause is better than adding additional
|
||||||
|
code to the \keyword{try} clause because it avoids accidentally
|
||||||
|
catching an exception that wasn't raised by the code being protected
|
||||||
|
by the \keyword{try} \ldots\ \keyword{except} statement.
|
||||||
|
|
||||||
|
|
||||||
When an exception occurs, it may have an associated value, also known as
|
When an exception occurs, it may have an associated value, also known as
|
||||||
the exceptions's \emph{argument}.
|
the exceptions's \emph{argument}.
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue