代码之家  ›  专栏  ›  技术社区  ›  Cino

如何以体面的方式处理Python异常?

  •  1
  • Cino  · 技术社区  · 3 年前

    我正在用python开发一个在线服务。由于这是一项在线服务,我在任何情况下都不希望该服务中断。所以我添加了很多 try.. except... 以确保如果发生任何不好的事情,我会抓住并报告。

    代码如下

    try:
        code here
    except Exception as e:
        reportException(e)
    
    some code here # I cannot put everything in a single `try...except` statement
    
    try:
        code here
    except Exception as e:
        reportException(e)
    

    我知道这是一种糟糕的方式,因为我必须使用 try 几次。我想知道有没有可能以一种优雅的方式做到这一点?

    2 回复  |  直到 3 年前
        1
  •  1
  •   Gavin Wong    3 年前

    您可以将try语句与循环结合起来:

    for action in [act_1, act_2, act_3, ...]:
        try:
            action(line)
        except:
            reportException()
    
        2
  •  0
  •   911    3 年前

    我认为更好的方法是在程序的最外层捕获异常,Django框架就是这样做的。事实上,在处理异常时,不建议捕捉“异常”异常,但如果您的项目要这样做,那么在程序的最外层捕捉它们会更优雅。例如,将所有代码放入“main”函数中,然后直接去捕获“main”功能抛出的异常。

    def main():
        # all your code and do not use try...except
        code here
        code here
        code here
    try:
        main()
    except Exception as e:
        reportException(e)