Best practise hierarchy for user-defined exceptions

Chris Rebert clp at rebertia.com
Mon Nov 17 07:05:51 EST 2008


On Mon, Nov 17, 2008 at 3:47 AM, Slaunger <Slaunger at gmail.com> wrote:
> Hi there,
>
> I am a newcomer to Pyhton coming from Java working on a relatively
> large Pyhton project with several packages and modules. To improve
> exception handling I would like to introduce some user-defined
> exceptions to distinguish between exceptions raised in self-written
> code as compared to std libray modules used there-in.
>
> Say, for instance I would like to define a MyParseError exception to
> indicate that something has gone wrong while parsing a byte string, a
> file, or while packing into or unpacking from a struct.Struct
> instance.
>
> Here is my stub-implemented idea on how to do it so far, which is
> inspired by how I would have done it in Java (but which may not be
> very Pythonic??):
>
> class MyException(Exception):
>
>    pass
>

The above class probably isn't necessary. You don't need to
overgeneralize this much.

> class MyStandardError(MyException, StandardError):
>
>    pass

Rename the previous class to just MyError in light of removing the other class.

>
> class MyParseError(MyStandardError, ValueError):
>
>   pass

This technique is very Pythonic. Subclass from both the exception
class for your module and from a built-in one if there's an applicable
one.

>
> Some comments and questions
>
> 1. The hierarchy is deliberately deep and maps to the std library such
> that it is easier to extend

Zen of Python: Flat is better than nested.
This is part of the reason I recommend removing the one class.

> 2. The implementations are empty but can be extended with hook for
> logging, statistics, etc.

True of stubs in general...

> 3. I use multiple inheritance in the two sub-classes. I have not tried
> that before. Is this A Good Thing or A Bad Thing to do?

Good in this case, just be careful to use super() if you override any methods.

> 4. Which __xx__ methods would you normally implement for the user-
> defined exception classes? I was thinking of __str__, for example? Is
> there a recommended __str__ idiom to use for that?

You might override __init__ if you want to store additional
information about the cause of the exception (e.g. location of parse
error, name of the rule the error occurred in, etc).
The __str__ inherited from Exception is usually sufficient, but you
can override it if you want to. it's a judgement call IMHO.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>
> -- Slaunger
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list