[Tutor] Why subclassing exceptions?

Mac Ryan quasipedia at gmail.com
Wed Sep 28 11:23:28 CEST 2011


On Wed, 28 Sep 2011 09:03:11 +0100
Alan Gauld <alan.gauld at btinternet.com> wrote:

> Remember that when handling exceptions we should be trying
> to recover the situation not just bombing with an error message. 
> Exceptions should not be thought of as purely about
> messages, they are opportunities to recover the situation without the 
> user even being aware that something went wrong. Only when recovery
> is impossible should we bomb out with a message.

Thank you Alan for the quick response. I totally see your logic, and
surely I can't (nor I wish to) argue with it in the context you
illustrated.

I have to say - however - that even after a few years of python
development I seldom use exceptions that way: in fact I can only
remember having subclassed error classes once, when I wrote a library
that was intended to be used by third-parties (for the exact same
reasons that you exemplified).

In all other cases (code that doesn't expose an API to third parties)
I consider that either my program works (and thus it can handle all
possible situations) or it does not, in which case - given that nothing
should silently fail - I'm happy for it to scream out loud with a raise
BaseException('<useful-debug-message-here>').

In fact, I use exceptions only when I can't write an ``assert``
statement concise enough. In the original code to which you initially
reacted I used an exception simply because it was more concise to put
it under the else clause rather then writing an ``assert`` statement
with all the if/else possibility it would have needed.

Is there any reason for which you (or anybody on the list, of course)
think I should avoid doing this?

/mac


More information about the Tutor mailing list