[Tutor] Why subclassing exceptions?

Alan Gauld alan.gauld at btinternet.com
Wed Sep 28 10:03:11 CEST 2011


On 28/09/11 07:33, Mac Ryan wrote:

>>>      raise BaseException('Something is wrong here!')
>>
>> Never raise BaseException directly!
> **I would like to know more on the rationale behind this
> guidelines, though.**
>
>>>> raise StandardError('This value should be True.')
>
> does the job in a much more elegant way than:
>
>>>> class ShouldBeTrueError(StandardError):
> ...
>>>> raise ShouldBeTrueError('Doh! An error!')

Can you explain why you think that is "more elegant"?
To me it looks ugly. If there are multiple errors
I need to open up the exception and test against
the message string (with all the dangers of mis-spelling
etc)

Compare:
try:  someFuncWithMultipleExceptions()
except StandardError, e:
        if e.message == "This value should be True":
              makeItTrue()
        elif e.message == "This value should be black":
              makeItBlack()
except ValueError:
      var = raw_input("oops, that's an invalid value, try again")

With
try:  someFuncWithMultipleExceptions()
except ShouldBeTrueError:
      makeItTrue()
except ShouldBeBlackError:
      makeItBlack()
except ValueError()
      var = raw_input("oops, that's an invalid value, try again")


The second form is more precise, more robust, and consistent
with the built in exception handling.

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. Otherwise you might as 
well do it this way:

if errorDetected:
    print "It's all gone terribly wrong"
    raise SystemExit



-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list