Python Custom Exception with Example

Python Custom Exception
Share this blog with others!

In the previous blog, we learned about Python Exception Handling using Try, Except, and Finally Statement. This time we will be learning how we can make our custom Error/Exception in python.

Read the previous blog i.e Python Multiple Exception Handling to understand this part better.

Let’s make our own Exception in Python.

Create Custom Exception in Python

As you have heard, Everything is an object in python. An Exception is also a class in python.

We can create an exception in python by inheriting the in-built class Exception in Python.

Let’s make our custom exception, which will raise an error when it encounters a number in a string. The Name of the Exception class will be NumberInStringException.

The name is long, but it explains the exception. You don’t need to know Object-Oriented programming in python in order to understand this concept. Stick with it and you will learn everything.

class NumberInStringException(Exception):
    pass


word = "HackTheDeveloper17"
for c in word:
    if c.isdigit():
        raise NumberInStringException(c)

In the above code, we defined a class with the name NumberInStringException which inherits the inbuilt python class Exception, which provides our class the Exception features. There is no code in the class, just the pass statement.

Next we defined a loop that checks for any number in the string value. If the character is a number the custom exception is raised.

Traceback (most recent call last):  
File ".\main.py", line 8, in <module>
    raise NumberInStringException(c)
__main__.NumberInStringException: 1 

Custom Error Message

We can also pass custom message while raising the exception.

Example:

>>> raise NumberInStringException("Number Found")

__main__.NumberInStringException: Number Found 

Learn how to create an iterator and range over it using Python Generator.

Customize Custom Exception Class

you must have thought why we just put the pass statement in the custom exception class. Can’t we change or override in-built exception class?

The Answer is yes, we can customize our custom exception class.

Let’s learn it via example:

In this example, we will further check the number found in the string. If the number is greater than 5, an exception will be raised else not.

class NumberInStringException(Exception):
    def __init__(self, number):
        self.number = number
        self.err = f"Number is {self.number} which is Greater than 5"
        super().__init__(self.err)


word = "HackTheDeveloper8"
for c in word:
    if c.isdigit() and int(c) > 5:
        raise NumberInStringException(c)

The above Python code defines a custom exception class, init function defines the values that it accepts while raising an exception. The Custom Exception class is like any other python class and can implement all features that a python class has.

Here, we are overriding the init function of the parent class i.e In-built Exception class of the python. The Parent class is then given the custom error message that needs to be printed.

Traceback (most recent call last):
  File ".\main.py", line 11, in <module>
    raise NumberInStringException(c)
__main__.NumberInStringException: Number is 8 which is Greater than 5

In this approach, we are not required to pass the custom message while raising the exception. The error message is created at the time of object creation of the exception class. Just the number is required to pass as the init function of the custom exception class needs one parameter value.

Best Practices while working with Custom Exceptions in Python

It’s always considered a good approach to keep all the custom exception classes in a separate python file and import it where you want to use it. It keeps our main python file lean and clean. This also increases readability.

Hope you like it!

Also, access the python tutorial to learn more about python like, list comprehension, Decorator, Inner Functions, Lambda Functions etc.

Learn more about python Custom Exception from python documentation.


Share this blog with others!

Leave a Comment

Your email address will not be published. Required fields are marked *