In a python program I am making, I want it to only take integers, and if it gets a string say "There has been an error in the system." instead of murmering sensless information the user will not understand
-
possible duplicate of Proper way to declare custom exceptions in modern Python? – hkk Dec 30 '13 at 17:39
-
2Isn't "There has been an error in the system." a good example of senseless information the user will not understand? :-) – RemcoGerlich Dec 30 '13 at 19:30
Use a try-except
block to capture the error and use the raise
statement to say the error message of your choice:
try:
a = int(input())
except:
raise Exception('There has been an error in the system')
-
Your solution provides a meaningful error message, but will still display the stack trace. The stack trace might scare off users, since it's mostly irrelevant to them. – Waleed Khan Dec 30 '13 at 17:30
You need to use a try
except
block to catch the error - see the documentation. Then you could just print
a message, and, if necessary, exit the program:
try:
value = int(input("Enter an integer: "))
except ValueError:
print("There has been an error in the system.")
input() # To let the user see the error message
# if you want to then exit the program
import sys
sys.exit(1)
If you do not want to add another indentation level by using a try-except
block, you can change the handling of all errors by adding the following to the beginning of your code:
import sys
def my_except_hook(exctype, value, traceback):
print('There has been an error in the system')
sys.excepthook = my_except_hook
In case of an error, only your specified error message is printed out.
import ctypes ctypes.windll.user32.MessageBoxW(None, u"CUSTOM MESSAGE", u"TITLE BAR", 0)