Python Raise Syntax

raise  {name_of_ the_ exception_class}

The basic way to raise an error is:

raise Exception(“user text”)

Checking whether an integer is odd or even

In the below code, we check if an integer is even or odd. if the integer is odd an exception is raised.  a  is a variable to which we assigned a number 5, as a is odd, then if loop checks if it’s an odd integer, if it’s an odd integer then an error is raised.

Python3




a = 5
 
if a % 2 != 0:
    raise Exception("The number shouldn't be an odd integer")


Output:

Checking Errror Type

We can check the type of error which have occurred during the execution of our code. The error can be a ‘ValueError’ or a ‘ZeroDivisionError’ or some other type of error.

Syntax: raise TypeError

Checking the error type

In the below code, we tried changing the string ‘apple’  assigned to s to integer and wrote a try-except clause to raise the ValueError. The raise error keyword raises a value error with the message “String can’t be changed into an integer”.

Python3




s = 'apple'
 
try:
    num = int(s)
except ValueError:
    raise ValueError("String can't be changed into integer")


Output

Python Raise Keyword

In this article, we will learn how the Python Raise keyword works with the help of examples and its advantages.

Similar Reads

Python Raise Keyword

Python raise Keyword is used to raise exceptions or errors. The raise keyword raises an error and stops the control flow of the program. It is used to bring up the current exception in an exception handler so that it can be handled further up the call stack....

Python Raise Syntax

raise  {name_of_ the_ exception_class}...

Raising an exception Without Specifying Exception Class

...

Advantages of the raise keyword

...