有什么方法可以在Python中引发多个异常吗?在以下示例中,仅引发第一个异常。
l = [0]
try:
1 / 0
except ZeroDivisionError as e:
raise Exception('zero division error') from e
try:
l[1]
except IndexError as e:
raise Exception('Index out of range') from e
还有其他办法吗?
一旦引发异常且未被捕获,程序的执行将停止。因此,在如此简单的脚本中只能启动一个异常。
如果您确实希望程序引发多个异常,那么您可以创建一个表示多个异常的自定义异常,并在 except 块内启动它。示例:
class ZeroDivAndIndexException(Exception):
"""Exception for Zero division and Index Out Of Bounds."""
I = [0]
try:
1 / I[0]
except ZeroDivisionError as e:
try:
I[1]
# Here you may raise Exception('zero division error')
except IndexError as e2:
raise ZeroDivAndIndexException()
我的解决方案有点长,但似乎有效:
class CustomError(Exception):
pass
l = [0]
exeps = []
try:
1 / 0
except ZeroDivisionError as e:
exeps.append(e)
try:
l[1]
except IndexError as e:
exeps.append(e)
if len(exeps)!=0:
[print(i.args[0]) for i in exeps]
raise CustomError("Multiple errors !!")
try:
pass
except AttributeError:
pass
except IndexError:
pass