[Tutor] Custom objects throw what exception?
Kent Johnson
kent37 at tds.net
Wed Apr 25 15:25:47 CEST 2007
Thanos Panousis wrote:
> The tutor list is definately helping me perform my OO-python babysteps.
>
> I want to ask this. Say I have some objects of my own, and using the
> example I posted in a previous post, say I have a person object with a
> instance variable called hairColor.
>
> The hairColor property is set via an exotic function that could go
> wrong and produce an exception.
>
> How should I hanlde this? Should I catch the exception in the
> person.__init__(self,color) "construtor"? and if I do so, what happens
> the code that is waiting for a person object to arrive with a call
> like p = person(). What exception should the person class throw, if
> any?
Don't hide the exception. If you can intelligently *handle* the
exception and create a person object that is initialized in a reasonable
way, do so. Otherwise let some kind of exception propagate back to the
caller so they know there is a problem.
If you catch the exception in person.__init__() then the code that calls
person() will get whatever person object you create. The caller will not
know that there was a problem with the color.
A ValueError might be appropriate. You can also define your own
exception for example
class HairColorError(Exception): pass
then in your code you can
raise HairColorError('%s is not a valid hair color' % color)
Kent
More information about the Tutor
mailing list