Throwing Custom Exception Types in Python
The default exceptions in Python cannot always satisfy all our needs in different situations. That is why Python has a built-in ability to create exceptions of your own type.
To create an exception, you need to declare a special OOP class using the keyword class. To the right of it, the name of the exception is written, and after the name in parentheses - the type of the exception:
class Exception(exception type): pass
Let's create our own class ToBigLength to catch lists that are too long. In the parentheses of this class, we'll write the type of exception that it will catch. Let it be the exception Exception. In the body of the class, we can write pass for now:
class ToBigLength(Exception):
pass
Let's check the operation of the exception we just created. To do this, we'll write the try-except construction, and throw our exception using the special raise command:
try:
raise ToBigLength
except ToBigLength:
print('error: list is too big')
After executing the code, the following will be displayed:
'error: list is too big'
Create an exception to catch a negative number.
Create an exception to catch zero.