Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python Raise Keyword

  • Difficulty Level : Easy
  • Last Updated : 28 Nov, 2021

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.

Syntax of the raise keyword :

raise  {name_of_ the_ exception_class}

The basic way to raise an error is :

raise Exception(“user text”)

Example:

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.

Input:

Python3




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

Output:

While raising an error we can also what kind of error we need to raise, and if necessary print out a text.

Syntax: 

raise TypeError

Example:

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 keyword raises a value error with the message “String can’t be changed into an integer”.

Input:

Python3




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

Output:

Raising an exception Without Specifying Exception Class

When we use the raise keyword, there’s no compulsion to give an exception class along with it. When we do not give any exception class name with the raise keyword, it reraises the exception that last occurred.

Example:

In the above code, we tried changing the string ‘apple’ to integer and wrote a try-except clause to raise the ValueError. The code is the same as before except that we don’t provide an exception class, it reraises the exception that was last occurred.

Input:

Python3




s = 'apple'
  
try:
    num = int(s)
except:
    raise

Output:

Advantages of the raise keyword:

  • It helps us raise exceptions when we may run into situations where execution can’t proceed.
  • It helps us reraise an exception that is caught.
  • Raise allows us to throw one exception at any time.
  • It is useful when we want to work with input validations.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!