Question about raise and exceptions.

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Wed Feb 28 17:49:49 EST 2007


Steven W. Orr a écrit :
> On Wednesday, Feb 28th 2007 at 22:03 +0100, quoth Bruno Desthuilliers:
> 
> =>Daniel Klein a ?crit :
> =>> On Wed, 28 Feb 2007 13:48:54 -0500 (EST), "Steven W. Orr"
> =>> <steveo at syslang.net> wrote:
> =>> 
> =>> 
> =>>>When I run it I get this:
> =>>>
> =>>>884 > ./t_fsm.py
> =>>>Traceback (most recent call last):
> =>>>  File "./t_fsm.py", line 3, in ?
> =>>>    from fsm import *
> =>>>  File "/home/boston/VIASAT/sorr/py/fsm/fsm.py", line 76
> =>>>    raise TransitionError, self.curr_state, newstate, "Going to error 
> =>>>state %d from state %d" % (self.curr_state, newstate)
> =>>>                                                    ^
> =>>>SyntaxError: invalid syntax
> =>> 
> =>> 
> =>> The arguments for TransitionError must be a tuple, 
> =>
> =>Err...
> =>
> =>> eg:
> =>> 
> =>> msg = "Going to error state %d from state %d" % (self.curr_state,
> =>> newstate)
> =>> raise TransitionError(self, curr_state, newstate, msg)

fix:

should be:
   raise TransitionError(self.curr_state, newstate, msg)
or
   raise TransitionError, (self.curr_state, newstate, msg)

(snip)
> 
> Ok. Now I'm potentially confused:
> 1. TransitionError takes 4 args

Almost (cf fix above).

> 2. raise takes a tuple with four elements after the exception argument as 
> its 2nd arg

No.

> I take it you mean #2?
> 
No.

the raise statement syntax is:
"raise" [typeOrInstance ["," value ["," traceback]]]

Most exceptions only take a single value (the error message), and it's 
very uncommon (at least in application code) to substitute another 
traceback.

Now back to the "value" part. If your exception type expects more than 
one arg, it's legal to use a tuple for the value(s). It will then be 
passed to the exception type (using *args expansion). It's legal, but it 
doesn't make the code much more readable. It's IMHO better to 
explicitely instanciate the exception with the needed params. Which of 
these two lines do you find the most readable ?

   raise TransitionError(self.curr_state, newstate, msg)
vs
   raise TransitionError, (self.curr_state, newstate, msg)

HTH



More information about the Python-list mailing list