异常后如何在同一行重试



我有以下代码:

def my_function:
#operation 1
#operation 2
...
#operation 99
#operation 100
def handle_exception:
#handle exception

现在,在执行my_function的任何部分,都可能发生异常。如果是,我想通过调用handle_exception方法来处理它。然后返回my_function,重试导致异常的相同操作。如果这次有效,请继续执行代码。异常可能发生在代码中的随机位置,我不想重试整个my_function。

例如。我正在执行我的函数(_F(。操作1工作正常。在操作2期间出现异常。我处理了异常,然后再次尝试操作2。这次有效,所以我继续操作。

这在Python中可能吗?

我会这样做:

def my_function(start = 0):
def operation1():
...
def operation2():
...
oper = [operation1, operation2]

for index in range(start, len(oper)):
try:
oper[index]()
except:
handle_exception(index)
break
def handle_exception(index):
#handle exception
my_function(index)

当然你需要函数handle_exception来解决这个问题,否则它将导致无限递归

下面是一个了解代码工作原理的示例:

def my_function(start = 0):
def operation1():
global i
print(i[2])
def operation2():
print(2)
oper = [operation1, operation2]
for index in range(start, len(oper)):
try:
oper[index]()
except:
handle_exception(index)
break
def handle_exception(index):
global i
i = ["a", "b", "c"]
my_function(index)
i = ["a", "b"]
my_function()

注意,函数handle_exception修复了i列表,因此不会有index error