How to create custom exceptions in Python?

Handling errors/exceptions are a most important skill which every developer must have. In programming, we often come across unexpected errors. So, In this python tutorial, we will discuss declaring custom exceptions in modern Python.

Table Of Contents

What are exceptions in Python?

We have two types of errors in Python programming language, which are Syntax Error and Exceptions. Errors that occur during compilation are called Syntax Error and Errors that occur during execution are called Exceptions.

In Python programming language, we also have an exception handling feature i.e. is using try-except.

Declaring custom exceptions in modern Python

Now we will create a custom exception class, for this we will define a class which will inherit from the built-in Exception class or other sub-classes of Exception class such as ValueError, TypeError, ZeroDivisionError.

See the below Example code, and then we will discuss the program and custom exceptions in modern Python.

Code Example 1

# created a class for custom exceptions.
class CustomUserException(Exception):
    '''Custom Exception Class'''

# Using try-except block. 
try:
    # raise is used to raise a CustomUserException.
    raise CustomUserException('An Error Detected through CustomUserException')
except CustomUserException as cux:
    print(cux)

OUTPUT :

An Error Detected through CustomUserException

In the above Example code 1, we have a CustomUserException class which inherits from the Exception class of Python. Python treats Docstring in the class as a statement. To raise CustomUserException we use raise statement, this raise statement raises the CustomUserException.

Code Example 2

# defining a custom error.
class StudentNotFoundError(Exception):
    # initializing attributes.
    first_roll = 1
    last_roll = 5

    # defined __init__ method.
    def __init__(self,roll):
        super().__init__(roll)
        self.roll = roll

    # defined a __str__ override method.
    def __str__(self):
        return f'The {self.roll} is not in a valid range {self.first_roll, self.last_roll}'


# main function.
def students(roll):
    # type conversion in int to check the range of roll numbers.
    roll = int(roll)
    # checking the range of rolls 
    if roll < StudentNotFoundError.first_roll or roll > StudentNotFoundError.last_roll:
        raise StudentNotFoundError(roll)

    # initialized a dict of students with roll and name.
    students = {'1': 'Dhoni',
                '2':'Kohli',
                '3':'Rahul',
                '4':'SKY',
                '5':'Rohit'}

    # initialized a dict with name and marks.
    marks = {'Rohit':476,
             'Dhoni': '498',
             'Kohli' : 592,
             'Rahul' : 420,
             'SKY' : 491 }

    # this stores name by roll number.
    name = students.get(str(roll))
    print(name, 'has obtained:', marks.get(name)/5,'%')


# taking an input of roll number.
roll = input("Enter Roll Number: ")

# exception handling with custom exceptions.
try:
    students(roll)
except StudentNotFoundError as snfe:
    print(snfe)

OUTPUT :

When Roll number is out of range (Exception Raised)

Enter Roll Number: 6
The 6 is not in a valid range (1, 5)

OUTPUT :

When Roll number is in range

Enter Roll Number: 3
Rahul has obtained: 84.0 %

So In the above examples, you can see we have a custom exception StudentNotFoundError which inherits from the Exception class of Python. This StudentNotFoundError raises an exception when the provided roll number is out of range. Here we have __str__ method which has been used to override and output a custom error string. Then student() function checks if the provided roll number is in range. If provided roll number is out of range then it raises an exception to StudentNotFoundError and prints the custom string which was created by __str__ method. If the provided roll number in range then it will get the name from the students dict and using the name it will print the marks of the student.

Summary

In this article, we learned about how to declare custom exception in modern python. Custom Exceptions can be raised by creating a class of custom exception which inherits from the Exception class. Also we learned about try-except and __str__ which are used for exception handling and override methods in python respectively.

Make sure to read and write above mentioned examples, in order to have a better understanding of this problem. Thanks.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top