1

as有没有办法通过使用关键字或 python 2.5 语法来定义多个异常的名称Exception, e?因此,如果您在这样的元组中定义带有异常的 try/except 子句,...except (RuntimeError, TypeError, NameError):也可以为错误分配名称,例如as (Rerr,Terr,Nerr)

还是我必须一一单独定义它们?

try:
    ....
except RuntimeError as Rerr:
    ....
except TypeError as Terr:
    ....
....
4

2 回答 2

6

You've misunderstood what the as keyword is doing. It's assigning the exception instance itself to the variable, not the class. So whichever type is caught by the except, it will end up in the as variable.

于 2012-08-20T11:18:33.213 回答
2

但是,如果您需要将它们分别命名,那么您可能会为每个定义单独的处理程序逻辑,在这种情况下,单独的定义有什么问题?

无论类型如何,您都可以为异常分配一个名称:

except (RuntimeError, TypeError, NameError) as e:
于 2012-08-20T11:19:10.763 回答