@@ -3318,17 +3318,29 @@ \section{Handling Exceptions \label{handling}}
3318
3318
When an exception occurs, it may have an associated value, also known as
3319
3319
the exception's \emph {argument }.
3320
3320
The 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}.
3324
3327
3325
3328
\begin {verbatim }
3326
3329
>>> 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
3332
3344
\end {verbatim }
3333
3345
3334
3346
If an exception has an argument, it is printed as the last part
0 commit comments