Python Raising Error With a Custom Message

In this article, we’ll see how to raise an error with a custom message in Python. We’ll learn how to use the ‘raise’ statement and we’ll practice this all with the help of examples.

What is the ‘raise’ statement?

The ‘raise’ statement allows you to throw/raise any error manually

For example:

raise Exception()

Running that results in an output like this:

Traceback (most recent call last):
  File "/home/", line 1, in <module>
    raise Exception()

We can also include a custom message of our choice when we raise an error.:

raise Exception ('I just raised my 1st ever Exception in Python!')

Running that code will result in an output like below:

Traceback (most recent call last):
 File "", line 1, in 
     raise Exception ('I just raised my 1st ever Exception in Python!')
 Exception: I just raised my 1st ever Exception in Python!

That’s the magic of the ‘raise’ statement!

Now let’s look through a couple of examples to master this concept!

Example#1 Age verification

age = int(input("Please enter your age. Make sure you're 18 or above: "))

if age < 18:
    raise ValueError("Minors are not eligible to vote!")
    print("You are eligible to vote, please continue.")

The above is a program that checks if a user is eligible to vote before it allows them to.

As soon as the program finds out the user is not eligible to vote, an appropriate error is raised with a user-friendly message terminating the program and not allowing the user to continue further. 

Example#2 Division using Try-Block

This time instead of using the if statement, we’ll use the try-block to directly catch the error and re-raise with our custom message:

print("Please enter 2 numbers to divide")

divider = input("divider: ")
dividend = input("dividend: ")

    result = (int(dividend )/int(divider))
    print(f"Your answer is {result}")
except ZeroDivisionError:
    raise ZeroDivisionError("Error! You cannot divide a number by 0. Please try again")
except ValueError:
    raise TypeError("Error! You did not enter a number. Please try again")

Here’s a breakdown:

  1. The program takes 2 numbers from the user and uses them to perform a division
  2. The operation is performed in a try-block to catch exceptions
  3. If the user entered 0 as the divider, the ZeroDivisionError will be triggered.
  4. We then catch this ZeroDivisionError in the except block. Then we raise again but with a friendly message explaining the problem to the user.
  5. If the user does not enter a number, the ValueError will be triggered when trying to convert it into an integer.
  6. We then catch this ValueError. We raise again but with a friendly message explaining the problem to the user.

In this way, we deal with various potential problems that can arise when the user enters invalid inputs.

Now that we have learnt the various ways of raising exceptions, the next logical step is to have a look at the other side of the coin and learn how to debug exceptions raised by others like a professional. To continue your learning I invite you to checkout out our video on that topic!

And with that, I will end this article.

Congratulations for making it to the end of the article, not many have the perseverance to do so!

I hope you enjoyed reading this article and found it useful!

Feel free to share it with your friends and colleagues!

If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!

Related Articles

Custom Exceptions in Python: Everything you need to know!

Python: Manually throw/raise an Exception using the “raise” statement

7 Most Common In-Built Exceptions in Python!

Exceptions in Python: Explained for Beginners!

Thanks to Namazi Jamal for his contributions to writing this article!

Photo of author
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn