[Tutor] best practice: throw exception or set a flag?

Alex Hall mehgcap at gmail.com
Fri Feb 4 14:03:28 CET 2011


On 2/4/11, Alan Gauld <alan.gauld at btinternet.com> wrote:
> "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.
There should have been a function below that which returned the object
with or without the error attribute.
>
>> 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.
Right, that second function should have done it, but I likely wrote it
wrong (what I get for making up an example on the spot).
>
> And most methods do not return the object of which they
> are a part (in Python at least, in SmallTalk they do).
That seems like it would get rather confusing...
>
> 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.
Will do, and I was talking about an object as in an instance of my
class, not generally, though I do like Python's model of treating
*everything* as an object.
>
>
>> 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.
Good to know. For this, I wanted my own exception, so I made this:
class ApiError(Exception):
 #for use with any bad requests from Bookshare's api

 def __init__(self, number, message):
  self.number=number
  self.message=message

 def __str__(self):
  return str(self.number)+": "+self.message

>
> Alan G.
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>


-- 
Have a great day,
Alex (msg sent from GMail website)
mehgcap at gmail.com; http://www.facebook.com/mehgcap


More information about the Tutor mailing list