I have some questions about user-defined exceptions in Python and how they should be organized in a complete project.
I have a fairly complex python project with some sub-packages that has the following structure (__init__.py omitted):
/docs (Documentation)
/apidocs (generated API documentation)
/askindex (my application package)
/test (Unit tests directory)
test_utils.py
... (more tests)
/workers (various worker classes)
communicators.py
processes.py
threads.py
utils.py
main.py (contains the starting point)
data_objects.py (various objects used all around the application)
settings.py (settings of the application)
README.txt
I would like to implement my own Exception to use them in the modules of the ‘workers’ package for specific errors.
Where should I place these exceptions ? I know that I should have my own base exception which subclasses the standard Exception class and subclass it for my other exceptions. Should I create a new ‘exceptions’ module under ‘workers’ ? Put exception classes in the module in which they’re raised ? In this case, where should I put my base class ? Is my application structure appropriated ?
I am new to exceptions in Python, so please excuse me if the answer is obvious…
In general I’ve found with my own work that when I want a custom type of exception, it’s specific to a particular module or package. If it’s relevant to a module, I put it just in that module. I haven’t yet found a case where it would be neater to have a module or package dedicated to exceptions.
Examples: if I have a
jestermodule, with a classJugglerin it with a methodjugglewhich can raise aDroppedBall(cue throwing rotten tomatoes or similar), theDroppedBallwould be in thejestermodule. Then thecrowd.Personinstances couldtrywatching the juggler andexcept jester.DroppedBall.If I had a package
food, with various modules in it,fruit,vegetable, etc. which all have aneatmethod (inherited fromfood.Foodstuff, doubtless), they might be able to raise aRottenException, which would naturally belong in the root of thefoodpackage:__init__.py.