From 6122d0267f37b2122a96fbe824efef3ae019266a Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Sat, 12 Jul 2003 01:05:37 +0000 Subject: SF patch #726751: Clarify docs for except target assignment Brett found that the tutorial didn't really explain what was happening with exception targets. Hopefully, this sheds some light on the subject. --- Doc/tut/tut.tex | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/Doc/tut/tut.tex b/Doc/tut/tut.tex index 05a8ea6..cffbf23 100644 --- a/Doc/tut/tut.tex +++ b/Doc/tut/tut.tex @@ -3318,17 +3318,29 @@ by the \keyword{try} \ldots\ \keyword{except} statement. When an exception occurs, it may have an associated value, also known as the exception's \emph{argument}. The presence and type of the argument depend on the exception type. -For exception types which have an argument, the except clause may -specify a variable after the exception name (or list) to receive the -argument's value, as follows: + +The except clause may specify a variable after the exception name (or list). +The variable is bound to an exception instance with the arguments stored +in \code{instance.args}. For convenience, the exception instance +defines \method{__getitem__} and \method{__str__} so the arguments can +be accessed or printed directly without having to reference \code{.args}. \begin{verbatim} >>> try: -... spam() -... except NameError, x: -... print 'name', x, 'undefined' -... -name spam undefined +... raise Exception('spam', 'eggs') +... except Exception, inst: +... print type(inst) # the exception instance +... print inst.args # arguments stored in .args +... print inst # __str__ allows args to printed directly +... x, y = inst # __getitem__ allows args to be unpacked directly +... print 'x =', x +... print 'y =', y +... + +('spam', 'eggs') +('spam', 'eggs') +x = spam +y = eggs \end{verbatim} If an exception has an argument, it is printed as the last part -- cgit v0.12