[Tutor] sys.exit() syntax error

Gonçalo Rodrigues op73418 at mail.telepac.pt
Tue Apr 6 05:35:15 EDT 2004


Em Tue, 06 Apr 2004 05:03:34 -0400, Gerald Wann <photonuv at kudos.net>
atirou este peixe aos pinguins:

>Hi -
>
>The answer to this is probably so trivial that i'll kick myself for 
>asking... ;-)
>
>i'm trying to use the sys.exit() function inside an error trap block and 
>the interpreter keeps telling me there's a syntax error e.g.
>
>import sys
>
>try:
>	open(file)
>except: IOError
            ^^^^^^^^

Should be (notice the position of the colon)

except IOError:

>	print 'blah'
>	print 'blah'
>	sys.exit()
>
>python doesn't like this... and says there's a syntax error at the 
>sys.exit() line
>
>however, when i dedent the sys.exit() call outside the except: block, it 
>runs just fine, (except for the fact that it shuts the whole thing down ;-)
>
>What am i missing here?
>

Exactly. Remember, the use of a : tells Python that a new block is
starting. Strictly speaking the : is redundant, because indenting
already tells Python so, but visually, the presence of the : helps a
lot.

Python complains with a syntax error because if the block is in the
same (that is

try:
    <code>
except:<code>

) then <code>. can only have one line (excluding continuation lines,
etc.). 

Something like

try:
    <code>
except: <code>
    <code>

Is ruled out -- and it is obvious isn't it. It's not indented right!


With my best regards,
G. Rodrigues



More information about the Tutor mailing list