How do I exit program in try/except?

exception, python

Solution

Use the sys.exit:

import sys

try:
    # do something
except Exception, e:
    print >> sys.stderr, "does not exist"
    print >> sys.stderr, "Exception: %s" % str(e)
    sys.exit(1)

A good practice is to print the Exception that occured so you can debug afterwards.

You can also print the stacktrace with the `traceback` module.

Note that the int you return in sys.exit will be the return code of your program. To see what exit code your program returned (which will give you information about what happens and can be automated), you can do:

echo $?

Problem

I have this try/except code: ``` document = raw_input ('Your document name is ') try: with open(document, 'r') as a: for element in a: print element except: print document, 'does not exist' ``` How do I exit the program after I print "[filename] does not exist"? `break` and `pass` obviously don't work, and I don't want to have any crashing errors, so `sys.exit` is not an option. Please ignore the `try` part - it's just a dummy.

Original source

Related problems