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 all of this with the help of examples.
Raising Exception
The ‘raise’ statement allows you to throw/raise any error manually.
For example:
raise Exception()
Traceback (most recent call last):
File "/home/main.py", line 1, in <module>
raise Exception()
Exception
Raising Exception with Custom Message
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!
In the above example, we have learned how to raise errors with a custom message using the built-in Exception class, we can also raise any other built-in exceptions instead of the Exception class if we need to.
If you wish to not use any built-in exceptions, you can also raise your own custom-made exceptions. You can learn how to do that in the article mentioned below.
Custom Exception In Python: Everything You Need To Know!
Now coming back to the topic, let’s look through a couple more examples to master this concept!
Example#1 Age verification
age = int(input("Please enter your age: "))
if age < 18:
raise ValueError("You are not eligible to vote!")
else:
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: Using Try-Except Blocks
Here’s another example, this time we’ll use the try-block to catch the error and then re-raise with our custom message in the except-block:
print("Please enter 2 numbers to divide")
numerator = input("numerator: ")
denominator = input("denominator: ")
try:
result = int(numerator)/int(denominator)
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:
- The program takes 2 numbers from the user and uses them to perform a division
- The operation is performed in a try-block to catch exceptions
- If the user entered 0 as the denominator, the ZeroDivisionError will be triggered.
- We then catch this ZeroDivisionError in the except block. Then we raise again but with a friendly message explaining the problem to the user.
- If the user does not enter a number, the ValueError will be triggered when trying to convert it into an integer.
- We then catch this ValueError. We raise again but with a friendly message explaining the problem to the user.
(If you want you can also catch multiple exceptions in a single except clause as shown here.)
In this way, we deal with various potential problems that can arise when the user enters invalid inputs.
Now that we have covered the topic of raising exceptions, next I invite you to learn how to debug exceptions the professional way.
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 Exception In Python: Everything You Need To Know!
Python: Manually throw/raise an Exception using the “raise” statement
Exceptions in Python: Explained for Beginners!
Thanks to Namazi Jamal for his contributions to writing this article!