Python User Defined Exceptions


User Defined Exceptions

A user-defined exception is the custom exception that inherits from the exception class.

Although, Python has many types of exceptions in the library, but all the exception cases cannot be thought. Many times, users also have their custom exception case.

In Python, we can create our own exception class, which is derived from the built-in Exception class.

Syntax:

In [ ]:
class UserDefinedException(Exception):
    pass

try:
    #content of try block
    pass
except UserDefinedException:
    passs

Example:

User defined exception.

In [1]:
#User defined exception
class InvalidAgeError(Exception):
    pass


age = 2
try:
    if age < 3:
        raise InvalidAgeError
    else:
        print("You are allowed to enter zoo.")

except InvalidAgeError:
    print("You are not allowed to enter zoo.")
You are not allowed to enter zoo.

Defining error_message function in user defined exception.

In [2]:
class InvalidAgeError(Exception):
    
    def error_message(self):
        print("You are not allowed to enter zoo.")

age = 2
try:
    if age < 3:
        raise InvalidAgeError
    else:
        print("You are alloweed to enter zoo.")

except InvalidAgeError as e:
    e.error_message()
You are not allowed to enter zoo.

Customizing User Defined Exception

Exception to pass custom message.

In [1]:
class InvalidAgeError(Exception):
    
    def __init__(self, age):
        self.age = age

    def error_message(self):
        print("You are not allowed, as you are", self.age,"years old.")
        

age = 2
try:
    if age < 3:
        raise(InvalidAgeError(age))
    else:
        print("You are alloweed to enter Zoo.")

except InvalidAgeError as e:
    e.error_message()
You are not allowed, as you are 2 years old.