python中可继承的自定义异常

2024-09-30 18:33:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为我的类创建一些自定义异常。我试图找出使这些异常类在派生类中可继承的最佳方法。本教程演示如何创建异常类。所以我这样做了:

我创造了一个基类.py公司名称:

class Error(Exception):
    """Base class for exceptions in BaseClass"""
    pass

class SomeError(Error):
    """Exection for some error"""
    def __init__(self, msg):
        self.msg = msg

class OtherError(Error):
    """Exection for some error"""
    def __init__(self, msg):
        self.msg = msg

class BaseClass():
    """Base test class for testing exceptions"""

    def dosomething(self):
        raise SomeError, "Got an error doing something"

还有一个derivedclass.py公司名称:

^{pr2}$

然后使用DerivedClass的测试:

#!/usr/bin/python
from derivedclass import DerivedClass,SomeError,OtherError

"""Test from within module"""
x = DerivedClass()
try:
    x.dosomething() 
except SomeError:
    print "I got some error ok"

try:
    x.doother()
except OtherError:
    print "I got other error ok"

如您所见,我将异常类从基类导入到派生类,然后再次从派生类导入到程序中。在

这似乎可以工作,但不是很优雅,我担心必须确保并在派生类模块中为所有异常类执行导入。在创建新的派生类时,似乎很容易忘记一个。然后,如果派生类的用户试图使用它,就会得到一个错误。在

有更好的方法吗?在

谢谢!在

-标记


Tags: 方法pyselffordefmsgerrorsome
3条回答

如果用户按名称导入错误类,他们会在import语句尝试执行时立即注意到问题:

ImportError: cannot import name FrotzError
File "enduser.py", line 7, in <module>
  from ptcmark.derivedclass import FrotzError

当然,您会记录下他们从哪里获得异常类,这样他们就可以查找异常类,然后更改代码以执行正确的操作:

^{pr2}$

So as you can see, I imported the exception classes from the base class into the derived class, then again from the derived class into the program.

您没有也不能将异常(或任何东西)从类导入到类中。从模块和(通常)导入模块中的内容。在

(通常,因为您可以将import语句放在任何范围内,但不建议这样做)

This seems to work ok, but is not very elegant, and I'm worried about having to make sure and do an import in the derived class module for all the Exception classes. It seems like it would be easy to forget one when creating a new derived class. Then a user of the derived class would get an error if they tried to use it.

派生类的模块没有理由需要从基类导入所有异常。如果您想让客户机代码更容易知道从何处导入异常,只需将所有异常放在一个名为“errors”或“exceptions”的单独模块中,这是Python中的一个常见习惯用法。在

另外,如果您在管理异常名称空间时遇到困难,可能是您的异常太细粒度了,您可以使用较少的异常类来处理。在

自定义异常必须导入其使用的所有模块中。在

此外,在derivedclass.py在

Wrong (because of the way its imported)
raise baseclass.OtherError, "Error doing other"

Fixed
raise OtherError, "Error doing other"

相关问题 更多 >