@@ -3318,17 +3318,29 @@ \section{Handling Exceptions \label{handling}}
33183318When an exception occurs, it may have an associated value, also known as
33193319the exception's \emph {argument }.
33203320The presence and type of the argument depend on the exception type.
3321- For exception types which have an argument, the except clause may
3322- specify a variable after the exception name (or list) to receive the
3323- argument's value, as follows:
3321+
3322+ The except clause may specify a variable after the exception name (or list).
3323+ The variable is bound to an exception instance with the arguments stored
3324+ in \code {instance.args}. For convenience, the exception instance
3325+ defines \method {__getitem__} and \method {__str__} so the arguments can
3326+ be accessed or printed directly without having to reference \code {.args}.
33243327
33253328\begin {verbatim }
33263329>>> try:
3327- ... spam()
3328- ... except NameError, x:
3329- ... print 'name', x, 'undefined'
3330- ...
3331- name spam undefined
3330+ ... raise Exception('spam', 'eggs')
3331+ ... except Exception, inst:
3332+ ... print type(inst) # the exception instance
3333+ ... print inst.args # arguments stored in .args
3334+ ... print inst # __str__ allows args to printed directly
3335+ ... x, y = inst # __getitem__ allows args to be unpacked directly
3336+ ... print 'x =', x
3337+ ... print 'y =', y
3338+ ...
3339+ <type 'instance'>
3340+ ('spam', 'eggs')
3341+ ('spam', 'eggs')
3342+ x = spam
3343+ y = eggs
33323344\end {verbatim }
33333345
33343346If an exception has an argument, it is printed as the last part
0 commit comments