如何在Python中使用“except”语句来处理多个异常?
可以使用相同的except子句定义多个异常。这意味着如果Python解释器找到匹配的异常,则将执行在except子句下编写的代码。
一般来说,多个异常的语法如下:
Except(Exception1, Exception2,…ExceptionN) as e:
当我们以这种方式定义except子句时,我们希望相同的代码引发不同的异常。此外,我们想在每种情况下都采取行动。
示例代码:
import sys
try:
d = 8
d = d + '5'
except (TypeError, SyntaxError) as e:
print(sys.exc_info())
我们得到的输出如下:
(<type 'exceptions.TypeError'>, TypeError("unsupported operand type(s) for
+: 'int' and 'str'",), <traceback object at 0x0000000002954748>)
更多Python相关文章,请阅读:Python 教程
极客教程