0

这很难解释,但我想知道是否有一种方法可以反复重试产生错误的代码行,直到它起作用。例如说我有代码:

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 行),然后继续执行其余的函数。另外,我希望错误处理在函数之外,而不是改变函数本身。

我希望这是有道理的,并感谢您的帮助:)

4

1 回答 1

0

你正在寻找一个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

于 2020-05-05T14:53:44.153 回答