[Tutor] Why subclassing exceptions?
Mac Ryan
quasipedia at gmail.com
Wed Sep 28 08:33:37 CEST 2011
On Wed, 28 Sep 2011 09:58:49 +1000
Steven D'Aprano <steve at pearwood.info> wrote:
> Mac Ryan wrote:
>
> > raise BaseException('Something is wrong here!')
>
> Never raise BaseException directly! BaseException is the very top of
> the exception hierarchy, you should raise the *most* specific
> exception you can, not the least specific. BaseException isn't even
> just for errors, it's also for flow control exceptions like
> StopIteration .
Fair enough! :) I just put that line to signal that there were cases
that weren't catch by the series of ``if``, but nevertheless you are
right.
**I would like to know more on the rationale behind this
guidelines, though.**
I explain: I already knew before that I should
subclass exceptions, nevertheless I very seldom do, as I feel like they
are just taking space on my screen doing nothing useful. All I need to
do is often just print out a useful message, so I find that
>>> raise StandardError('This value should be True.')
does the job in a much more elegant way than:
>>> class ShouldBeTrueError(StandardError):
...
... '''
... Custom Error triggered in case a value should be True.
... '''
...
... pass
...
>>> raise ShouldBeTrueError('Doh! An error!')
Ok, I already hear some of you screaming out loud "Anathema!!" ;) ...yet
could somebody please clarify why should I bother subclassing? [I'm
positive there is a good reason, but in all honesty I can't imagine
which one...].
Thanks,
/mac
More information about the Tutor
mailing list