Skip to content

Python custom exception

  • by

Python custom exception is possible by creating a new class that is derived from the built-in Exception class.

class MyException(Exception):
    pass

Or better (maybe perfect), instead of pass give a docstring:

class MyException(Exception):
    """Raise for my specific kind of exception"""

Or

class CustomError(Exception):
    ...
    pass

try:
   ...

except CustomError:
    ...

Python custom exception

Simple example code where CustomError is a user-defined error which inherits from the Exception class.

class CustomError(Exception):
    "Raised when the input value is less than 18"
    pass


number = 18

try:
    input_num = int(input("Enter a number: "))
    if input_num < number:
        raise CustomError
    else:
        print("Eligible to Vote")

except CustomError:
    print("Exception occurred: Invalid Age")

Output:

Python custom exception

Do comment if you have any doubts or suggestions on this Python exception-handling topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading