Raising an Exception
In Python, the raise statement is used to explicitly raise an exception. It allows you to generate a specific exception and provide additional information about the error.
The basic syntax of the raise statement is as follows:
raise <ExceptionType>("Optional error message")
Example: Raise an error and stop the program if x is lower than 0
x = -1
if x < 0:
raise Exception("Sorry, no numbers below zero")
You can also define what kind of error to raise, and the text to print to the user:
Example: Raise a TypeError if x is not an integer
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")