An Exception is raised whenever there is an error encountered, and it signifies that something went wrong with the program. By default, there are many exceptions that the language defines for us, such as
TypeError when the wrong type is passed. In this article, we shall look at how we can create our own Custom Exceptions in Python.
But before we take a look at how custom exceptions are implemented, let us find out how we could raise different types of exceptions in Python.
Python allows the programmer to raise an Exception manually using the
The below function raises different exceptions depending on the input passed to the function.
def exception_raiser(string): if isinstance(string, int): raise ValueError elif isinstance(string, str): raise IndexError else: raise TypeError
>>> exception_raiser(123) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 3, in exception_raiser ValueError >>> exception_raiser('abc') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 5, in exception_raiser IndexError >>> exception_raiser([123, 456]) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 7, in exception_raiser TypeError
As you can observe, different types of Exceptions are raised based on the input, at the programmer’s choice. This allows for good flexibility of Error Handling as well, since we can actively predict why an Exception can be raised.
Defining Custom Exceptions
Similarly, Python also allows us to define our own custom Exceptions. We are in complete control of what this Exception can do, and when it can be raised, using the
raise keyword. Let us look at how we can define and implement some custom Exceptions.
1. Create a Custom Exception Class
We can create a custom Exception class to define the new Exception. Again, the idea behind using a Class is because Python treats everything as a Class. So it doesn’t seem that outlandish that an Exception can be a class as well!
All Exceptions inherit the parent
Exception Class, which we shall also inherit when creating our class.
We shall create a Class called
MyException, which raises an Exception only if the input passed to it is a list and the number of elements in the list is odd.
class MyException(Exception): pass def list_check(lst): if len(lst) % 2 != 0: raise MyException # MyException will not be raised list_check([1, 2, 3, 4]) # MyException will be raised list_check([1, 3, 5])
[email protected]:~# python3 exceptions.py Traceback (most recent call last): File "exceptions.py", line 12, in <module> list_check([1, 3, 5]) File "exceptions.py", line 6, in list_check raise MyException __main__.MyException
2. Add a custom Message and Error
We can add our own error messages and print them to the console for our Custom Exception. This involves passing two other parameters in our
MyException class, the
Let us modify our original code to account for a custom Message and Error for our Exception.
class MyException(Exception): def __init__(self, message, errors): # Call Exception.__init__(message) # to use the same Message header as the parent class super().__init__(message) self.errors = errors # Display the errors print('Printing Errors:') print(errors) def list_check(lst): if len(lst) % 2 != 0: raise MyException('Custom Message', 'Custom Error') # MyException will not be raised list_check([1, 2, 3, 4]) # MyException will be raised list_check([1, 3, 5])
Printing Errors: Custom Error Traceback (most recent call last): File "exceptions.py", line 17, in <module> list_check([1, 3, 5]) File "exceptions.py", line 11, in list_check raise MyException('Custom Message', 'Custom Error') __main__.MyException: Custom Message
We have thus successfully implemented our own Custom Exceptions, including adding custom error messages for debugging purposes! This can be very useful if you are building a Library/API and another programmer wants to know what exactly went wrong when the custom Exception is raised.
In this article, we learned how to raise Exceptions using the
raise keyword, and also build our own Exceptions using a Class and add error messages to our Exception.
- JournalDev article on Custom Exceptions
- Exception Handling in Python