r/pythonhelp • u/vintagefancollector • Aug 03 '21
How do I print a custom error message without Python returning a traceback?
I have 2 programs that require a numerical input. One takes a float, the other takes an integer.
If they detect letters or symbols, it's supposed to return the error message "That wasn't a float/number!"
While it does return the error message, they also return Traceback (most recent call last): NameError: name 'Example' is not defined together with the error message.
How do I make it return ONLY the error message without the Traceback thing?
3
Upvotes
1
u/MrPhungx Aug 03 '21
The problem you have is a bit different. You are catching the ValueError. The traceback of the ValueError is not printed on the console as you would want. However another exception occurs that you simply don't catch. In your positive number code for example you are defining retrieve_positive_number inside of the try block. However you try to do something with it outside of it, although it is only visible in the scope of the try block. That's why you get a NameError. The variable is not defined. Try to move the code for the positive case (the user enters a valid number) inside of the try block.