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
-
5Isn'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
7 Answers
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')

- 13,287
- 9
- 35
- 66
-
1Your 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
-
4Do not use a bare except as this can hide errors. Use the appropriate except...https://docs.python.org/3/library/exceptions.html#exception-hierarchy – theQuestionMan Nov 04 '20 at 05:20
Using try
, except
and raise
Since ValueError
inherits from the Exception
class, the first parameter when creating a ValueError
object is the message it prints:
try:
int("string") #the code that raises the error
except ValueError:
raise ValueError("Your custom message here.")
This prints:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
ValueError: invalid literal for int() with base 10: 'string'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError: Your custom message here.
If you don't want the previous error chain to print, put from None
in the raise
statement:
try:
int("string") #the code that raises the error
except ValueError:
raise ValueError("Your custom message here.") from None
This prints:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError: Your custom message here.
I suggest you leave the chain because it gives more information, like what was inputted that raised the error. If you want to include the information from the original error in the custom message, use the error's attributes:
from traceback import format_tb
try:
int("string") #the code that raises the error
except ValueError as err:
raise ValueError("Custom message with traceback and original message\n" + format_tb(err.__traceback__)[0] + err.args[0] + "\nEnd of error message.") from None
This prints
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ValueError: Custom message with traceback and message
File "<stdin>", line 2, in <module>
invalid literal for int() with base 10: 'string'
End of error message.
Though this allows for customization of the error's print, the code is a little unpythonic.
Using assert
Because in the question you said you wanted to block all strings, you can use assert
and isinstance()
:
obj = "a string" #the input you want to raise the error on
assert not isinstance(obj, str), "Your custom message here."
This prints:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: Your custom message here.
Though using assert
looks clean, the error won't carry as much information because it would be a generic AssertionError
. Raising a ValueError
tells more information about what caused the error at a glance.

- 484
- 3
- 6
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)

- 10,650
- 8
- 44
- 61
If you want to make an error, you use raise. Here is an example:
raise SyntaxError('MUHAHA THIS IS A ERROR')

- 89
- 1
- 5
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. In addition, this prevents the stack trace from being displayed.

- 15,891
- 14
- 50
- 76
Use raise Exception('There has been an error in the system')
may be useful for most cases but you may also need create meaningful errors for specific systems.
Eg.
class ExpiredTaxIdException(Exception):
def __init__(self):
Exception.__init__(self, 'Tax ID expired')
Then you can call it on your code, sample:
from your_execeptions_file import ExpiredTaxIdException
class ClientsController:
def is_profile_valid(client):
if client.tax_id.is_valid == False:
raise ExpiredTaxIdException()
return True
# eg. you call it on your API on another place of your code that can't accept invalid tax_id
try:
ClientsController().verify_client(client)
except ExpiredTaxIdException as e:
return {'error': str(e)}
>>> { "error": "Tax ID expired" }

- 359
- 2
- 21
You can try this..
import ctypes
ctypes.windll.user32.MessageBoxW(None, u"CUSTOM MESSAGE", u"TITLE BAR", 0)

- 1,716
- 10
- 23