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 $?
Answer from Charles Menguy on Stack OverflowUse 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 $?
Just re-raise it. It's more friendly for developer
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'
raise
Check python document in the Raising Exceptions section about re-raise error in except.
Try/Except issue with exiting program on error : Forums : PythonAnywhere
quit() in while loop not wokring with try-except block
Python won't spit out sys.exit message in try function
How do I exit a program in a try/except block in Python through a function? - Stack Overflow
What is try/except in Python?
How do you catch a specific exception?
What is the finally clause?
For some reason the quit() function is not working for me in a while loops while using the try and except block. In the try block, once it goes to the quit() line, it automatically goes to the except block.
Anyone have any ideas why?
For instance, in the code below, after printing "hello" it goes to the except when trying to run quit()
while True:
try:
print("hello")
quit()
except:
print("hello")
I don't understand why the try/except in this sample, will not exit gracefully, and instead continues to try to calculate the rate.
I thought the try/except caused a program to exit, if the except gets executed:
hours = raw_input("how long worked: ")
rate = raw_input("pay rate: ")
try:
hours = float(hours)
rate = float(rate)
except:
print "[+] Error -- Please enter numeric input "
if hours > 40:
rate *= 1.5
total = hours * rate
print "you made %s dollars" % total This is the error I receive:
c:\home\dev\tutorial>python payrate.py
how long worked: five
pay rate: 4
[+] Error -- Please enter numeric input
Traceback (most recent call last):
File "payrate.py", line 10, in <module>
rate *= 1.5
TypeError: can't multiply sequence by non-int of type 'float'Cheers.