【问题标题】:What are the unknown issues of using try/except block in functions in python? [closed]在 python 的函数中使用 try/except 块有哪些未知问题? [关闭]
【发布时间】:2019-09-17 07:00:05
【问题描述】:

我想知道在以下方法中使用 try/except 块的副作用或未知问题?

方法一:

def f1():
    try:    
        # some code here
    except Exception as e:
        print(str(e))
def f2():
    try:
        f1()
    except Exception as e:
        print(str(e))

方法 2:与方法 1 中的逻辑相同,但在 f1() 中没有 try/block

def f1():
    # some code here

def f2():
    try:
        f1()
    except Exception as e:
        print(str(e))

方法 3:使用多个嵌套函数

def f1():
    # some code here

def f4():
    # some code here

def f3():
    f4()
    # some code here

def f2():
    try:
        f1()
        f3()
    except Exception as e:
        print(str(e))

方法 4:在每个函数中添加多个 try/except

def f1():
    try:
        # some code here
    except Exception as e:
        print(str(e))

def f4():
    try:
        # some code here
    except Exception as e:
        print(str(e))

def f3():
    try:
        f4()
        # some code here
    except Exception as e:
        print(str(e))

def f2():
    try:
        f1()
        f3()
    except Exception as e:
        print(str(e))

【问题讨论】:

  • 根据定义,我们不知道。

标签: python try-except


【解决方案1】:

知道在代码中的何处捕获异常是一项重要的设计选择,并且通常取决于您期望捕获的异常。

存在“冒泡”异常的概念——如果在内部函数中引发异常但没有try 块,则异常将向上传递给调用它的函数。这一直持续到满足适当的except 语句并处理异常,或者它到达顶层并导致程序以堆栈跟踪终止。

因此,选择在何处处理异常取决于您希望函数抛出哪些异常,然后在代码中的适当位置处理这些异常,例如您可以在其中向用户返回有意义的消息并要求他们重试。您定义的任何方法都没有明显错误,但这取决于函数引发的内容以及您希望如何处理异常。

值得注意的是,except Exception 是不好的做法,因为这甚至会捕获键盘中断(用户按 CTRL+C)。在可能的情况下,您应该处理您调用的函数引发的特定异常(应该在函数文档中)并采取适当的措施。

有用的背景https://docs.python.org/3/tutorial/errors.html

【讨论】:

    【解决方案2】:

    当使用 try/except 静默失败是危险的。在我看来,可重用函数没有太多关于调用者希望如何处理异常的上下文(信息),最好抛出异常由调用者处理。

    如果您正在处理可重用函数的异常,那么它的行为应该是可预测且一致的。比如你可能想返回后备值,或者你想抛出另一个错误,为用户提供足够的上下文等

    所以我更喜欢调用者处理异常的方法 3

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2022-01-23
      • 2022-06-15
      • 1970-01-01
      相关资源
      最近更新 更多