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

Alex Hall mehgcap at gmail.com
Fri Feb 4 01:41:17 CET 2011


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 an object, even if said object has an
error and may therefore not have data beyond an error code and
message? 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? I assume so...
except e:
 print e.message

or something like that. I know I have research to do about the
specifics of all this, but before I go off and look it all up I am
wondering if it is the best way to go as far as standards and best
coding practices. This is still that api wrapper, so I am not the only
one who may end up using this file and I want to make it into
something that is useable and does what people expect. TIA.


-- 
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