tags:

views:

91

answers:

3

Hi,

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

A: 

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"
Harun Prasad
Oops - I was trying it different ways, and forgot to take out that. Fixed it in the post. Thanks
ptcmark
A: 

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.

You did not, and cannot, import exceptions (or anything) from classes and into classes. You import things from modules and (usually) into modules.

(usually, because you can put import statements in any scope, but it is not recommended)

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.

There is no reason the module of the derived class would need to import all the exceptions from the base classes. If you want to make it easy for client code to know where to import exceptions from, just put all your exception in a separate module named "errors" or "exceptions", that's a common idiom in Python.

Also, if you have trouble managing your namespace of exceptions, maybe your are being too fine-grained with your exceptions, and you could do with fewer exception classes.

ddaa
Ahh... Ok, if I move that all to a separate module, I don't have to worry about them in the derived class. - CoolI'm not really creating those exception classes, I just need one special exception. I was just trying what was in the tutorial on http://docs.python.org. ;-)Thanks for the help on the 'pythonic' (that is the correct term, right?) way to do it!
ptcmark
A: 

If the user imports your error classes by name, they'll notice the problem as soon as the import statement tries to execute:

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

And of course you'll document where they're supposed to get the exception classes from, so they'll just look it up and then change their code to do the right thing:

from ptcmark.errors import FrotzError
Jason Orendorff
That said, I've seen whole programs that never need to handle specific types of exception, except in a very small number places. As ddaa says, intricate exception hierarchies are not really the Python way.
Jason Orendorff
So using my little test as an example, I should create a module baseclass.errors, correct? -Thanks!
ptcmark
You might want to make a *package* that contains baseclass, derivedclass, and errors. http://docs.python.org/tutorial/modules.html#packages
Jason Orendorff