What are Exceptions in Python?
Here’s what Python.org says about an exception in Python:
Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal.
Reference: https://docs.python.org/3/tutorial/errors.html
If I put this simply, an exception is a flag that disrupts the typical flow of the program, but doesn’t stop the program itself. It can basically raise errors or handle each case by case.
Create Custom Exceptions in Python
There are cases where you want to raise your own exceptions for your particular case. And there is an easy way to do that in Python. You define a custom exception class that inherits the base Exception class. And you just use that in your code. Here’s an example:
class YourOwnException(Exception):
pass
from custom_exceptions import YourOwnException
try:
raise YourOwnException('This is your own custom exception!')
except YourOwnException as e:
print(e)
"""
Output:
This is your own custom exception!
"""
That’s it! Now you learned how to create a custom exception in Python. You can copy code from this github repo.