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
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.
The code below demonstrates a program that raises an error if the value of the variable x
is lower than :
# Inputx = -1# Use of "raise"if x < 0:raise Exception("Sorry, no numbers below zero")
The code above takes the following actions:
In line 2, the value of x
is initialized as .
In line 5, the condition checks whether the value of x
is less than . 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.