Preferred exception style?

George Young gry at ll.mit.edu
Fri May 30 15:32:08 EDT 2003


On Fri, 30 May 2003 12:51:49 -0600, Steven Taschuk wrote:

> Quoth Dave Benjamin:
>> I was just wondering which style you prefer for raising exceptions. I never
>> really thought about it much, but I was looking at some code today that said:
>> 
>> raise SomeException, 'some relevant message'
>> 
>> and I tend to do it like this:
>> 
>> raise SomeException('some relevant message')
>> 
>> The two forms seem to have identical results. Any reason to prefer one over
>> the other? Which do you use?
> 
> They are, as you suspect, synonymous.
> 
> The standard library mostly uses the syntax with a comma.  I much
> prefer the syntax with parentheses, so much so that I've (just a
> moment ago, in fact) submitted a PEP to eliminate the former.
> 
> I don't like the former because, in short, it's a holdover from
> the days of string exceptions and is ill-suited to instance
> exceptions.  (The PEP has a more complete account of my reasons;
> rather than amplify here, I'll just wait for it to be numbered and
> post it in its entirety.)

Furthermore, the parenthesis form allows for more than just
a string value.  E.g.:
class GetRunFailed(Exception):
	def __init__(self, reqobj, dberrormsg=None,
                     domainerr='Run does not exist'):
		self.reqobj=reqobj
		self.dberrormsg=dberrormsg
		self.domainerr=domainerr
	def __str__(self):return '%s: dberror: %s, explanation: %s'%\
				 (self.reqobj,self.dberrormsg,self.domainerror)
...
raise GetRunFailed(self.request, dberrormsg=dbcursor.geterror(),
                   domainerror='Run %s not found in folder %s' %\
                                       (self.run,self.db.name)


-- George




More information about the Python-list mailing list