Skip to content

Python exception class

  • by

Python exception class is the base class from which exceptions inherit. The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.

The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions.

Creating Exception Class

class JustException(Exception):
    def __init__(self, message):
        print(message)

Python exception class

Simple example code of Creating User-Defined Exception in Python

# Base class
class PerError(Exception):
    pass


# Exception class for percentage > 100
class InvalidPerError(PerError):
    def __init__(self):
        super().__init__("Percentage is invalid")


# Exception class for percentage < 80
class LessPerError(PerError):
    def __init__(self):
        super().__init__("The Percentage is lesser than the Cut-off.")


# class to check percentage range
class checkPer(PerError):
    def __init__(self, per):
        if per < 80:
            raise LessPerError
        if per > 100:
            raise InvalidPerError
        print("Congrats you're Enrolled")


# different cases and output
try:
    print("For Percentage: 93")
    checkPer(93)
except Exception as e:
    print(e)

try:
    print("For Percentage: 102")
    checkPer(102)
except Exception as e:
    print(e)

try:
    print("For Percentage: 58")
    checkPer(58)
except Exception as e:
    print(e)

Output:

Python exception class

Which classes are exception classes in Python?

Answer: All exception classes are derived from the BaseException class. The BaseException is the base class of all other exceptions. The Python Exception Hierarchy is like this below.

  • BaseException
  • Exception
    • ArithmeticError
      • FloatingPointError
      • OverflowError
      • ZeroDivisionError
      • AssertionError
      • AttributeError
      • BufferError
      • EOFError
      • ImportError
        • ModuleNotFoundError
      • LookupError
        • IndexError
        • KeyError
      • MemoryError
      • NameError
        • UnboundLocalError
      • OSError
        • BlockingIOError
        • ChildProcessError
        • ConnectionError
          • BrokenPipeError
          • ConnectionAbortedError
          • ConnectionRefusedError
          • ConnectionResetError
      • FileExistsError
      • FileNotFoundError
      • InterruptedError
      • IsADirectoryError
      • NotADirectoryError
      • PermissionError
      • ProcessLookupError
      • TimeoutError
  • ReferenceError
  • RuntimeError
    • NotImplementedError
    • RecursionError
  • StopIteration
  • StopAsyncIteration
  • SyntaxError
    • IndentationError
      • TabError
  • SystemError
  • TypeError
  • ValueError
    • UnicodeError
      • UnicodeDecodeError
      • UnicodeEncodeError
      • UnicodeTranslateError
  • Warning
    • BytesWarning
    • DeprecationWarning
    • FutureWarning
    • ImportWarning
    • PendingDeprecationWarning
    • ResourceWarning
    • RuntimeWarning
    • SyntaxWarning
    • UnicodeWarning
    • UserWarning
  • GeneratorExit
  • KeyboardInterrupt
  • SystemExit

Do comment if you have any doubts or suggestions on this Python exception 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

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