我想为我的类(class)创建一些自定义异常。我试图找出使这些异常类在派生类中可继承的最佳方法。本教程展示了如何创建异常类。所以我这样做了:
我创建了一个baseclass.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:
from baseclass import BaseClass,SomeError,OtherError
class DerivedClass(BaseClass):
def doother(self):
"""Do other thing"""
raise OtherError, "Error doing other"
然后是使用 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"
如您所见,我将异常类从基类导入派生类,然后再从派生类导入程序。
这似乎工作正常,但不是很优雅,我担心必须确保并在派生类模块中为所有异常类导入。在创建新的派生类时似乎很容易忘记一个。然后,如果派生类的用户尝试使用它,他们将收到错误消息。
有更好的方法吗?
谢谢!
-标记
请您参考如下方法:
自定义异常必须在其使用的所有模块中导入。
另外,derivedclass.py也有错误
Wrong (because of the way its imported)
raise baseclass.OtherError, "Error doing other"
Fixed
raise OtherError, "Error doing other"
