Python raise Keyword

Raises an exception when a condition is true. The exception can then be caught by other code with the except keyword.

Example

Python
def divide(n, d):
    if d == 0:
        raise Exception("Dividing by 0 is not allowed")
    return n / d

try:
    divide(10, 0)
except Exception as e:
    print(e)

Output

Dividing by 0 is not allowed

Notes

In addition to exceptions that Python can raise, you can raise your own exceptions. This is often used to verify that parameters to a function have the expected values or range of values. Other languages often use the term "throw" which is the equivalent of Python's raise keyword.

You can define your own exceptions as well, which are classes derived from Python's Exception class.

Example

Python
class ZeroNotAllowed(Exception):
    pass

def divide(n, d):
    if d == 0:
        raise ZeroNotAllowed
    return n / d

try:
    divide(10, 0)
except ZeroNotAllowed:
    print("Zero is not allowed in the denominator.")

Output

Zero is not allowed in the denominator.