使用两个函数引发异常,无法按预期捕获异常

时间:2020-07-28 13:23:47

标签: python exception raiserror

代码在这里:

def funcFail():
    try:
        raise Exception("Failed externally")
        print("Should not print")
    except Exception as e:
        print(f"Exception : {e}")
        raise Exception(f"Exception in occured due: {e}")
    finally:
        return "This is finally block :P"
        print("This is finally block :P")

def checkexpcep():
    global k 
    k = []
    try:
        funcFail()
    except Exception as e:
        print(f"Exception out : {e}")
        k.append(str(e))
    finally:
        return "nothing"

checkexpcep()

预期:

"Exception : Failed externally"
"This is finally block :P"
"Exception out : Exception in occured due: Failed externally"

输出:

"Exception : Failed externally"

2 个答案:

答案 0 :(得分:0)

下次尝试使用python调试器(任何想法都足够好,pycharm或wing等。)。无论如何,请在下面的代码中查看我的嵌入式注释编号:

def funcFail():
    try:
        # (2)
        raise Exception("Failed externally")
        print("Should not print")
    except Exception as e:
        print(f"Exception : {e}")
        # (3)
        raise Exception(f"Exception in occured due: {e}")   
    finally:
        # (4)
        return "This is finally block :P"
        print("This is finally block :P")

def checkexpcep():
    global k 
    k = []
    try:
        # (1)
        funcFail()
        # (5)
    except Exception as e:
        print(f"Exception out : {e}")
        k.append(str(e))
    finally:
        return "nothing"

checkexpcep()

调用checkexpcep()后,您到达代码中的点1。然后调用funcFail()并到达点2,在2处引发一个异常,该异常被except块锁定,并且在打印完异常,您在点3处引发了新的异常,并且到达了3块并由python执行(请注意,最终始终执行)。您将从带有字符串finally的finally块返回。此内容浅或隐藏了先前的异常。返回值将使您指向"This is finally block :P"。返回值不执行任何操作,程序成功完成。

答案 1 :(得分:0)

如果您确实想要预期的输出,只需将returnfinally块中移出即可:

def funcFail():
    try:
        raise Exception("Failed externally")
        print("Should not print")
    except Exception as e:
        print(f"Exception : {e}")
        raise Exception(f"Exception in occurred due: {e}")
    finally:
        print("This is finally block :P")
    return "This is finally block :P"

def checkexpcep():
    global k 
    k = []
    try:
        funcFail()
    except Exception as e:
        print(f"Exception out : {e}")
        k.append(str(e))
    finally:
        return k,"nothing"

print(checkexpcep())

输出:

Exception : Failed externally
This is finally block :P
Exception out : Exception in occurred due: Failed externally
(['Exception in occurred due: Failed externally'], 'nothing')

(请注意,我在末尾添加了tuple的打印以显示k的值)