[英]Raising multiple exception in python
Is there any way to raise multiple exceptions in python?有没有办法在python中引发多个异常? In the following example, only the first exception is raised.在以下示例中,仅引发第一个异常。
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
Is there any other way?还有其他方法吗?
Once an exception is raised and not catched, the execution of your program will stop.一旦引发异常但未被捕获,程序的执行将停止。 Hence, only one exception can be launched in such a simple script.因此,在这样一个简单的脚本中只能启动一个异常。
If you really want your program to raise multiple exceptions, you could however create a custom Exception representing multiple exceptions and launch it inside an except block.如果您真的希望您的程序引发多个异常,您可以创建一个表示多个异常的自定义异常并在 except 块中启动它。 Example:例子:
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()
Here my solution a bit long but seems to work :这里我的解决方案有点长,但似乎有效:
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 !!")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.