Inheritable custom exceptions in python
<p>I want to create some custom exceptions for my class.  I am trying to figure out the best way to make these exception classes inheritable in derived classes. The tutorial shows how to create the Exception classes.   So I did that like this:</p>

<p>I created a baseclass.py:</p>

<pre><code>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"
</code></pre>

<p>And a derivedclass.py:</p>

<pre><code>from baseclass import BaseClass,SomeError,OtherError

class DerivedClass(BaseClass):

    def doother(self):
        """Do other thing"""
        raise OtherError, "Error doing other"
</code></pre>

<p>Then a test that uses the DerivedClass:</p>

<pre><code>#!/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"
</code></pre>

<p>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. </p>

<p>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.</p>

<p>Is there a better way to do this?</p>

<p>Thanks!</p>

<p>-Mark</p>
