Besides the built-in Python exceptions, it is also possible to define your own exceptions. Such user-defined exceptions should inherit from the base class Exception. This can be useful when you define your own classes such as the polynomial class in Section 19.1.
Take a look at this small example of a simple user-defined exception:
class MyError(Exception): def __init__(self, expr): self.expr = expr def __str__(self): return str(self.expr) try: x = random.rand() if x < 0.5: raise MyError(x) except MyError as e: print("Random number too small", e.expr) else: print(x)
A random number is generated. If the number is below 0.5, an exception is thrown and a message that the value is too small is printed. If no exception is raised, the number is printed.
In this example, you also saw a case of using else in a try statement. The block under else ...