raise - To raise an exception
Raises an exception when a condition is true. The exception can then be caught by other code with the
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)
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
You can define your own exceptions as well, which are classes derived from Python's
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.")
Zero is not allowed in the denominator.