Inheritable custom exceptions in python
Question: 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:

I created a 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"
    

And a derivedclass.py:

    
    
    from baseclass import BaseClass,SomeError,OtherError
    
    class DerivedClass(BaseClass):
    
        def doother(self):
            """Do other thing"""
            raise OtherError, "Error doing other"
    

Then a test that uses the 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"
    

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.

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.

Is there a better way to do this?

Thanks!

-Mark


Answer: The custom exceptions has to be imported in all modules its used in.

Also, there is an error in derivedclass.py

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

