how to abort on syntax errors

kyosohma at gmail.com kyosohma at gmail.com
Mon Mar 26 14:16:03 EDT 2007


On Mar 26, 1:07 pm, Steve Holden <s... at holdenweb.com> wrote:
> kyoso... at gmail.com wrote:
> > On Mar 26, 12:21 pm, "Josh" <n... at nowhere.com> wrote:
> >> I have a lot of except Exception, e statements in my code, which poses some
> >> problems. One of the biggest is whenever I refactor even the triviallest
> >> thing in my code.
>
> >> I would like python to abort, almost as if it were a compile-time error,
> >> whenever it cannot find a function, or if I introduced a syntax error. But,
> >> instead, it merrily proceeds on its way.
>
> >> Is there some idiom that you use in situations like these?
> >> thanks,
> >> josh
>
> > Try sticking in an
>
> > try:
> >   #do something
> > except SyntaxError, e:
> >    print e
> >    sys.exit(0)
> > except Exception, e:
> >    print e
>
> > # You put in as many exceptions as you like.
>
> Of course the main problem with this solution is that a piece of code
> will raise a syntax error when it's compiled (i.e. at module import
> time, or when the main program starts up). So in the case where "#do
> something" has a syntax error it won;t be trapped because the program
> hasn't got to execution by the time the error is detected.
>
> regards
>   Steve
> --
> Steve Holden       +44 150 684 7255  +1 800 494 3119
> Holden Web LLC/Ltd          http://www.holdenweb.com
> Skype: holdenweb    http://del.icio.us/steve.holden
> Recent Ramblings      http://holdenweb.blogspot.com

You're right, Mr. Holden. Drat! I stupidly assumed that he meant some
code executed first and then it'd hit one of his syntax errors. Either
way though, it would get "caught"...either by the interpreter (IDLE)
or the exception. At least, that's been my experience with syntax
errors.

I get a warning from IDLE that tells me there's an error at so-and-so.
Or the program just chokes and throws out and error after doing some
calculations and I learn once again that I didn't close a string.

Mike




More information about the Python-list mailing list