how to abort on syntax errors

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Mon Mar 26 18:37:01 EDT 2007


On Mon, 26 Mar 2007 13:21:22 -0400, Josh 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?

Yes. Don't use "except Exception".

Seriously. You almost always should only catch the specific type of
exception that you expect, and treat anything else as a real error and let
it actually halt the program. e.g. instead of something like this:

try:
    do_something_complicated()
except Exception, e:
    # Missing key or invalid index?
    print "Exception $s occurred!" % str(e)
    handle_missing_key_or_index()


do this:

try:
    do_something_complicated()
except KeyError:
    print "Lost key"
    handle_missing_key()
except IndexError:
    print "Missing key"
    handle_index_error()




In my opinion, the only real use for "except Exception" is something like
this:


if __name__ == "__main__"":
    try:
        main()
    except Exception:  # or just "except:"
        print "A fatal error occurred, but what it is is a secret."
        sys.exit(1)
    finally:
        cleanup()



-- 
Steven.




More information about the Python-list mailing list