+ 3
How to customize exceptions messages in Python
I want to show custom messages to the user whenever an exception is raised, and not show traceback, the line nor the name of the exception. The farther I got was this (example from the IDLE prompt): >>> raise ValueError("Input is not a number.") Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> raise ValueError("Input is not a number. Try again.") ValueError: Input is not a number. Try again. But I want the message to be like this: Input is not a number. Try again. What can I do to accomplish it?
3 Respostas
+ 6
This is what I do:
num = 0
try:
print("Enter the number to process: ", end="")
num = int(input())
except ValueError:
print("Input is not a number. Try again.")
+ 6
As John said, if you want a completely custom error message, don’t raise an exception: print your own message. Then build your code around it so that the program stops like it does when an error occurs (unless of course there’s already an exception happening, like in John’s example).
+ 2
Thank you both, John and Pedro. That's exactly what I had in mind.