如何避免在尝试使用多个说明时出错?

时间:2019-03-26 18:48:08

标签: python

我遇到此代码问题:

def stupid_function():
    try:
        stupid_instruction1()
        stupid_instruction2()
    except:
        pass

当看到stupid_instruction1()中的错误时,它甚至不会尝试运行stupid_instruction2()。有什么办法吗? (谢谢)

2 个答案:

答案 0 :(得分:0)

您可以在两个不同的try块中运行这两个函数:

def stupid_function():
    try:
        stupid_instruction1()
    except:
        pass
    try:
        stupid_instruction2()
    except:
        pass

需要说明的是,您实际上不应排除所有错误,而应该仅排除特定错误。

答案 1 :(得分:0)

stupid_instruction2()是否需要尝试? 如果可以,我建议将try/catch放在要调用的函数中(如果它是您自己的函数)。如果不是您自己的函数,则将其包装如下:

def my_stupid_instruction2():
    try:
        stupid_instruction2()
    except:
         pass

如果您想让stupid_instruction2()被呼叫,无论如何都可以这样做。

示例:

def stupid_function():
    try:
        stupid_instruction1()
    except: # As Luke pointed out, it is bad practice to do a general exception
        pass
    finally:
        stupid_instruction2() # This will be run regardless if the try fails