[Tutor] best practice: throw exception or set a flag?
Emile van Sebille
emile at fenx.com
Fri Feb 4 01:58:33 CET 2011
On 2/3/2011 4:41 PM Alex Hall said...
> Hi all,
> I am wondering what the best way to do the following would be: throw
> an exception, or always return an object but set an error flag if
> something goes wrong? Here is an example:
>
> class c:
> def __init__(self):
> self.error=False
> def func(self, val):
> if val!=10: self.error=True
>
> someObj=c()
> someObj.func(5)
> if someObj.error: #do stuff
>
> OR:
>
> class c:
> def __init__(self):
> self.error=False
> def func(self, val):
> if val!=10: throw ValueError #I know the syntax is wrong
>
> someObj=c()
> try:
> someObj.func(5)
> except:
> #do stuff
>
> Which is the "standard" way when dealing with objects? Throw
> exceptions or always return
Yes, throw exceptions and always return the expected result. Expecting
non-class (ie, external to the class) access to verify that the result
is usable would be , I think, generally frowned upon.
Emile
More information about the Tutor
mailing list