[Tutor] best practice: throw exception or set a flag?
Alan Gauld
alan.gauld at btinternet.com
Fri Feb 4 10:39:39 CET 2011
"Alex Hall" <mehgcap at gmail.com> wrote
> 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:
Throw an exception is the short general case answer...
> class c:
> def __init__(self):
> self.error=False
> def func(self, val):
> if val!=10: self.error=True
But note that neither of these methods returns "an object"
- unless you count None as an object of course.
> Which is the "standard" way when dealing with objects? Throw
> exceptions or always return an object, even if said object has an
> error and may therefore not have data beyond an error code and
> message?
I'm not sure what you have in mind here but remember that
init() is an initialiser and not really a constructor so the object
already exists when init() is called. init() does not return the
object.
And most methods do not return the object of which they
are a part (in Python at least, in SmallTalk they do).
But if you are using object in the general sense of a return
value (since everything in Python is an object) then yes
you should return an object and let the exception signal
failure.
> If I go the exception route, can I somehow put a message into
> the exception, maybe adding it as an attribute of my custom
> exception
> class?
Yes, or you can just pass a string to any exception when you raise it.
Alan G.
More information about the Tutor
mailing list