![](/img/trans.png)
[英]How skip over an iteration in a for loop when an exception occurs Python
[英]How to skip execution if an exception occurs in Python
我正在尝试在下面的代码中进行异常处理。 如果有异常,它应该跳过 try 块中的下一个语句,并应该直接转到 except 块并继续循环。
from functools import reduce
def sumnumbers(list_elements):
try:
sum = reduce(lambda x, y: x + y, list_elements)
return sum
except Exception as e:
print("Error in function", list_elements)
a = [[1,2],[3,"hi"],[5,6],[7,8],[9,"hello"]]
for i in a:
try:
s = sumnumbers(i)
print("hello ", i)
except Exception as e:
print(e)
pass
实际输出:
hello [1, 2]
Error in function [3, 'hi']
hello [3, 'hi']
hello [5, 6]
hello [7, 8]
Error in function [9, 'hello']
hello [9, 'hello']
预期输出:
hello [1, 2]
Error in function [3, 'hi']
hello [5, 6]
hello [7, 8]
Error in function [9, 'hello']
嗨,首先,您可以查看此处以更深入地了解异常在 python 中的工作原理。
from functools import reduce
def sumnumbers(list_elements):
try:
sum = reduce(lambda x, y: x + y, list_elements)
return sum
except Exception as e:
raise Exception("Error in function", list_elements)
a = [[1,2],[3,"hi"],[5,6],[7,8],[9,"hello"]]
for i in a:
try:
s = sumnumbers(i)
print("hello ", i)
except Exception as e:
print(e)
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.