how to abort on syntax errors

skip at pobox.com skip at pobox.com
Mon Mar 26 20:04:20 CEST 2007


    Josh> I have a lot of except Exception, e statements in my code, which
    Josh> poses some problems. One of the biggest is whenever I refactor
    Josh> even the triviallest thing in my code.

    Josh> I would like python to abort, almost as if it were a compile-time
    Josh> error, whenever it cannot find a function, or if I introduced a
    Josh> syntax error. But, instead, it merrily proceeds on its way.

    Josh> Is there some idiom that you use in situations like these?

In general, I think you should be more specific in the exceptions you
catch.  For example, if you want to look up a key in a dictionary and most
of the time it's there, but every now and again you need to add it, I'd use
something like this:

    try:
        val = somedict[key]
    except KeyError:
        # need to initialize slot
        somedict[key] = INITIAL_VALUE

That is, be as precise as you can in the exceptions you catch.  Also, try to
keep the body of the try block as small as you can.

Skip



More information about the Python-list mailing list