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
- ZeroDivisionError
- ImportError
- TypeError
- ModuleNotFoundError
Exceptions
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'
Custom Exceptions
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?
You create a class that inherits from the exception class
>>> class CustomException(Exception):
... def __init__(self, statement, s):
... self.statement = statement
... self.s = s
... print(self.statement)
...
You can also add a pass statement instead of a constructor.
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)
>>>
Top comments (0)