You are going to learn how to create a Python user defined exception.
There's all kinds of exceptions like ZeroDivisionError, IndexError, ImportError, TypeError and more.
Python is packed with several built-in exceptions like
Python will show those exceptions when something goes wrong like:
>>> x = 1 / 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero
or loading a non existing module
>>> import life Traceback (most recent call last): File "<stdin>", line 1, in <module> ModuleNotFoundError: No module named 'life'
However you can Create your own personalized exceptions Python allows us to create our exception from the exception base class.
Python usually throws exceptions in the try-except statement.
try: #statement or line of code except customError: #statement or line of code
All kinds of exceptions can be raised. So how do you make your own exception type?
>>> class CustomException(Exception): ... def __init__(self, statement, s): ... self.statement = statement ... self.s = s ... print(self.statement) ...
Then you can raise your own exceptions:
>>> raise CustomException("went wrong", 3) went wrong Traceback (most recent call last): File "<stdin>", line 1, in <module> __main__.CustomException: ('went wrong', 3) >>>