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.
Use an else clause right after the try-except block. The else clause will get hit only if no exception is thrown. The else statement should always precede the except blocks. In else blocks, you can add code which you wish to run when no errors occurred.
finally ..." in Python. In Python, try and except are used to handle exceptions (= errors detected during execution). With try and except , even if an exception occurs, the process continues without terminating. You can use else and finally to set the ending process.
The try… except block is completed and the program will proceed. However, if an exception is raised in the try clause, Python will stop executing any more code in that clause, and pass the exception to the except clause to see if this particular error is handled there.
exit() method is used to terminate the process with the specified status. We can use this method without flushing buffers or calling any cleanup handlers. Example: import os for i in range(5): if i == 3: print(exit) os._exit(0) print(i) After writing the above code (python os.
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 $?
Using
sys.exit(1)
is not a crashing error, it's a perfectly normal way to exit a program. The exit code of 1 is a convention that means something went wrong (you would return 0 in the case of a successful run).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With