Skip to main content
 首页 » 编程设计

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

2024年10月25日9soundcode

什么更好?

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

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