如何仅重试函数中的错误生成行
How to retry only error-producing line in a function
这很难解释,但我想知道是否有一种方法可以只重复重试产生错误的代码行,直到它起作用。例如说我有代码:
def unreliabelfunction():
#Line 1 of code
#Line 2 of code (sometimes produces an error and sometimes works)
#Line 3 of code
#Error handling should go where function is called, rather than inside the function.
unreliablefunction()
我想要某种错误处理,它会持续 运行 第 2 行直到它起作用(无需重新 运行 宁第 1 行),然后继续执行其余功能。另外,我希望错误处理在函数之外,而不是改变函数本身。
我希望这是有道理的,感谢您的帮助:)
您正在寻找 try: except
区块。
这是一个粗略的例子。
def unreliabelfunction():
line_1()
try_wrapper(line_2())
line_3()
# Pass a function to try_wrapper
def try_wrapper(fn, args):
successful = False
while not successful:
try:
# Execute the function.
fn(*args)
# If it doesn't cause an exception,
# update our success flag.
successful = True
# You can use Exception here to catch everything,
# but ideally you use this specific exception that occurs.
# e.g. KeyError, ValueError, etc.
except Exception:
print("fn failed! Trying again.")
查看文档:https://docs.python.org/3/tutorial/errors.html#handling-exceptions
这很难解释,但我想知道是否有一种方法可以只重复重试产生错误的代码行,直到它起作用。例如说我有代码:
def unreliabelfunction():
#Line 1 of code
#Line 2 of code (sometimes produces an error and sometimes works)
#Line 3 of code
#Error handling should go where function is called, rather than inside the function.
unreliablefunction()
我想要某种错误处理,它会持续 运行 第 2 行直到它起作用(无需重新 运行 宁第 1 行),然后继续执行其余功能。另外,我希望错误处理在函数之外,而不是改变函数本身。
我希望这是有道理的,感谢您的帮助:)
您正在寻找 try: except
区块。
这是一个粗略的例子。
def unreliabelfunction():
line_1()
try_wrapper(line_2())
line_3()
# Pass a function to try_wrapper
def try_wrapper(fn, args):
successful = False
while not successful:
try:
# Execute the function.
fn(*args)
# If it doesn't cause an exception,
# update our success flag.
successful = True
# You can use Exception here to catch everything,
# but ideally you use this specific exception that occurs.
# e.g. KeyError, ValueError, etc.
except Exception:
print("fn failed! Trying again.")
查看文档:https://docs.python.org/3/tutorial/errors.html#handling-exceptions