简体   繁体   中英

Inheritable custom exceptions in python

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

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"

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM