]> granicus.if.org Git - python/commitdiff
SF patch #726751: Clarify docs for except target assignment
authorRaymond Hettinger <python@rcn.com>
Sat, 12 Jul 2003 01:05:37 +0000 (01:05 +0000)
committerRaymond Hettinger <python@rcn.com>
Sat, 12 Jul 2003 01:05:37 +0000 (01:05 +0000)
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

index 05a8ea633ddbea1f1c20aa388bf03a3a32c9f0f2..cffbf23d77c3f67ac58b8973aa90ab3339849145 100644 (file)
@@ -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
+...
+<type 'instance'>
+('spam', 'eggs')
+('spam', 'eggs')
+x = spam
+y = eggs
 \end{verbatim}
 
 If an exception has an argument, it is printed as the last part