【问题标题】:raise Exception not catching exception as expected with two functions使用两个函数引发异常未按预期捕获异常
【发布时间】:2020-07-28 13:23:47
【问题描述】:

这是代码:

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"

【问题讨论】:

  • 显然return中的finallyswallows例外。
  • @quamrana,有没有其他选择,或者我应该在没有 finally 的情况下继续吗?
  • 我还建议使用自定义异常,可能会使这样的代码更容易调试:docs.python.org/3/tutorial/errors.html#user-defined-exceptions
  • 你应该使用finally来整理是否有异常。只有在没有异常的情况下要返回东西时才使用return <something>,所以看起来returnfinally格格不入。

标签: python exception raiserror


【解决方案1】:

下次尝试使用python调试器(任何ide都足够好,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,然后到达finally 块,python 执行它(注意,最后总是执行)。您从 finally 块返回字符串 "This is finally block :P".this 浅或隐藏先前的异常。返回将带您指向5。返回值什么都不做,程序成功结束。

【讨论】:

    【解决方案2】:

    如果您确实想要您的预期输出,那么只需将 return 移出 finally 块:

    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 的值)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      • 2012-06-05
      • 2023-02-12
      • 2019-11-02
      • 2017-10-03
      相关资源
      最近更新 更多