Python’s Raise Keyword

Original article was published by Sohaib Ahmad on Artificial Intelligence on Medium


The keyword raise is used when the coder wants to bring forward an exception conditional on something occurring. As an example, the syntax is as follows:

if test:
raise Exception(Message)

Given this, we could use it as follows:

    #Input:
string = "Ciao"

if string=="Ciao" or string=="Howdy" or string=="Bye":
raise Exception("This word is not allowed")

#Output:
Exception: This word is not allowed

As you can see here — if the condition passes (in this case, the string does indeed say ‘Hello’, then the exception is raised. Likewise:

# Input a positive number and raise an exception 
# if input is a negative value

num = int(input("Enter a positive number: "))

if num<0:
raise Exception("Please input only positive value ")

print("num = ", num)

which will give the result:

First run:
Enter a positive number: 20
num = 20

Second run:
Enter a positive number: -10
Traceback (most recent call last):
File "/home/main.py", line 10, in <module>
raise Exception("Please input only positive value ")
Exception: Please input only positive value

So as you can see, once the user inputs a number that is not a positive integer, the specific exception that we defined has been raised. This is great because now, we have control over a specific common problem that can arise, giving us more control over our code.

The keyword raise is super easy to use. All you need to do is be clear on what you’re trying to test for and what you want to do once you’ve found it.