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

huangapple go评论72阅读模式
英文:

How to handle Python exceptions in a decent way?

问题

I am developing an online service with python. Since it is an ONLINE service, I do not want the service down under any circumstances. So I add lots of try.. except... to make sure that if anything bad happens I will catch it and report it.

code like this

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)

I know it is a bad way as I have to use try several times. I want to know is it possible to do this in an elegant way?

英文:

I am developing an online service with python. Since it is an ONLINE service, I do not want the service down under any circumstances. So I add lots of try.. except... to make sure that if anything bad happens I will catch it and report it.

code like this

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)

I know it is a bad way as I have to use try several times. I want to know is it possible to do this in an elegent way?

答案1

得分: 1

你可以将try语句与循环结合使用:

for action in [act_1, act_2, act_3, ...]:
    try:
        action(line)
    except:
        reportException()
英文:

You can combine try statements with a loop:

for action in [act_1, act_2, act_3, ...]:
    try:
        action(line)
    except:
        reportException()

答案2

得分: 0

我认为更好的方式是在程序的最外层捕获异常,这就是Django框架所做的。实际上,在处理异常时,不推荐捕获"Exception"异常,但如果你的项目要这样做,最好在程序的最外层捕获它们更加优雅。例如,将所有代码放入"main"函数中,然后直接捕获"main"函数抛出的异常。

def main():
    # 所有代码都放在这里,不要使用try...except
    代码在这里
    代码在这里
    代码在这里

try:
    main()
except Exception as e:
    报告异常(e)
英文:

I think a better way is to catch exceptions at the outermost layer of your program, which is what the Django framework does. In fact, when handling exceptions, it is not recommended to catch "Exception" exceptions, but if your project is going to do this, it is more elegant to catch them at the outermost layer of the program.For example, put all your code into the "main" function, then go directly to catch the exception thrown by the "main" function.

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)

huangapple
  • 本文由 发表于 2023年5月6日 16:25:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/76187885.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定