gpt4 book ai didi

python - 在 python 中处理异常的首选方法

转载 作者:太空宇宙 更新时间:2023-11-04 03:34:59 24 4
gpt4 key购买 nike

什么更好?

class CustomException(Exception):
pass

class CustomSomething(object):
def do_something(self, xml):
try:
lxml.etree.parse(xml)
except LxmlError as e: # LxmlError class is only example
raise CustomException(e)

或者只是

class CustomSomething(object):
def do_something(self, xml):
lxml.etree.parse(xml)

什么时候应该使用 try/except block 并引发自定义异常,什么时候应该让调用我的函数的任何东西处理它?<​​/p>

最佳答案

一般来说,当您只是引发另一个异常时,我认为不需要添加 try/except block 。通常,您引发的异常与您正在调用的异常引发的异常几乎相同(因为问题仍然相同)。这不受我能找到的任何官方文档的支持(“[s]imple is better than complex ”除外);我能找到的最好的是the list of built-in exceptions ,上面写着:

When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module, and subclass that to create specific exception classes for different error conditions

不过,这似乎只是解释了如何创建自定义异常,而不是何时

关于python - 在 python 中处理异常的首选方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29527543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com