What is the raise keyword in Python?

The raise keyword in Python is mainly used for exception handling. Exception handling handles exceptions or errors so that the system does not malfunction due to incorrect code.

The main tools in exception handling are:

  • try and except
  • finally
  • raise

Solution

The raise keyword raises a specific exception when a condition is met or the code encounters an error.

The exception raised by the program may either be an exception instance or an exception class. When you use the raise keyword, you can define what kind of error the machine should raise for a particular exception.

Code

The code below demonstrates a program that raises an error if the value of the variable x is lower than 00:

# Input
x = -1
# Use of "raise"
if x < 0:
raise Exception("Sorry, no numbers below zero")

Explanation

The code above takes the following actions:

  • In line 2, the value of x is initialized as 1-1.

  • In line 5, the condition checks whether the value of x is less than 00. Since x is a negative number, the condition is satisfied.

  • In line 6, an exception is raised with the raise keyword. The code produces an error that corresponds to the message associated with the exception.

The raise keyword can be helpful for developers, as statements that are easy to decipher can be printed to signify errors.

Free Resources