Raise Custom Exception with Error Code and Message in Python

In Python, we can create custom exceptions by creating a new class. This new class needs to be derived from the built-in Exception class.

To raise a custom exception with error code and message in Python, we can do the following:

First, create a exceptions.py file and create a custom exception class:

class CustomException(Exception):
    def __init__(self, code, message):
        self.code = code
        self.message = message

Now, we can use the above custom exeception in the following manner:

from exceptions import CustomException

def divide(divident, divisor):
    if divisor == 0:
        raise CustomException(400,"Cannot divide a number by 0")    
    result = divident/divisor 
    return result 
#Calling divide function
The above code will give the following error:
Traceback (most recent call last):
File "\example\exception_main.py", line 11, in <module>
divide(5, 0)
File "\example\exception_main.py", line 6, in divide
raise CustomException("400", "Cannot divide a number by 0")
exceptions.CustomException: ('400', 'Cannot divide a number by 0')