Custom Exception Handling in Python

Hello folks, In the previous post we have got the basic understanding of Exception handling in python. And, Today’s agenda will be custom exception handling – how we can force raise an exception, define and create custom Exception classes.

Let us imagine you need to write a code to validate your input and the validation criteria is input should be an integer and it should be between 1 to 10. If the validation criteria fail, we have to throw valid exceptions.

My first solution will be something like this.

def isvalid_input(val):
    try:
        if(val > 0 and val <= 10):
            print('input is valid')
        else:
            print("input is invalid")
    except Exception as ex:
        print(ex)

But in this code we have ignored various scenarios like

  • Input maybe not integers and then mathematical operators will not work and it will throw an exception.
  • we are not actually raising an exception if the validation criteria do not match.

Raise Custom Exception

so let us say how can we force raise any exception. To do it, we use the raise keyword in python. so modify the above code and use the raise keyword in the else block.

def isvalid_input(val):
    try:
        if(val > 0 and val <= 10):
            print('input is valid')
        else:
            raise Exception("Input is Invalid")
    except Exception as ex:
        print(ex)

Create Custom Exception Class

Now what we want to do is to handle the validation criteria and throw custom exceptions based on validation criteria. so create custom Exception classes.

class VALRANGEERROR(Exception):
    def __init__(self,message):
        self.message=message
        super().__init__(self.message)

Here we have created a class called VALRANGEERROR and setting its message in constructor so that we can provide custom messages while raising this exception. After this modify our method to raise our custom Exception class.

def isvalid_input(val):
    try:
        if(val > 0 and val <= 10):   
            print('input is valid')
        else:
            raise VALRANGEERROR("Input is not in range")
    except ValueError as ex:
        print(f"Value Error - {ex}")
    except VALRANGEERROR as ex:
        print(f"Custom Exception - {ex}")
    except Exception as ex:
        print(ex)

So, to summarise this, use the raise keyword to force raise an exception. To implement a custom Exception class, Create a class that inherits from class Exception and assigns the message field in the constructor.

Leave a Reply

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