How to customize exceptions messages in Python | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

24th Feb 2018, 9:51 PM
Pedro Maimere
Pedro Maimere - avatar
3 Answers
+ 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.")
24th Feb 2018, 10:04 PM
John Wells
John Wells - avatar
+ 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).
24th Feb 2018, 10:12 PM
Pedro Demingos
Pedro Demingos - avatar
+ 2
Thank you both, John and Pedro. That's exactly what I had in mind.
25th Feb 2018, 6:02 PM
Pedro Maimere
Pedro Maimere - avatar